코딩테스트/99클럽
99클럽 코테 스터디 31일차 TIL - Bad Grass
꼽파
2024. 8. 23. 09:59
function numIslands(grid) {
if (grid.length === 0) return 0;
const directions = [
[-1, 0], [1, 0], [0, -1], [0, 1],
[-1, -1], [-1, 1], [1, -1], [1, 1]
];
let count = 0;
function dfs(x, y) {
if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] === '0') {
return;
}
grid[x][y] = '0'; // Mark this cell as visited by setting it to '0'
for (let [dx, dy] of directions) {
dfs(x + dx, y + dy);
}
}
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] !== '0') {
count++;
dfs(i, j);
}
}
}
return count;
}
728x90