๋ฌธ์
ํ์ด ๊ณผ์
์ฌ์ ๊ฐ์๋ฅผ ์ธ์ด์ฃผ๋ DFS
ํ์ ๋ฌธ์ ์
๋๋ค.
๊ฐ๋จํ ๋ฌธ์ ์ด์ง๋ง ํ๋ ์ผ์ด์ค ๋๋ฌธ์ ์กฐ๊ธ ํค๋งธ์ต๋๋ค. LeetCode
๋ฌธ์ ๋ ๊น๋ํ์ง๋ง ์
๋ ฅ ์ ํ ์ฌํญ์ด ๋ช
์๋์ด์์ง ์์ ๊ฒฝ์ฐ๊ฐ ์์ด์ ๋๊ฐํ ์ํฉ์ด ์ข
์ข
๋ฐ์ํ๋ ๊ฒ ๊ฐ์ต๋๋ค.
(์
๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ grid
๊ฐ ๋น์ด์๋ ๊ฒฝ์ฐ๊ฐ ์กด์ฌํ ๊ฒ์ด๋ผ๊ณ ์๊ฐ์ ๋ชปํ์ต๋๋ค..)
๋๋ฌธ์ ๋ฌธ์ ๋ฅผ ํ ๋๋ ์ฌ๋ฌ edge case
๋ฅผ ๊ณ ๋ คํ๋ ์ฐ์ต์ด ํ์ํด๋ณด์
๋๋ค.
์ฝ๋
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function (grid) {
const dx = [0, 0, 1, -1];
const dy = [1, -1, 0, 0];
if (!grid.length) {
return 0;
}
const N = grid.length,
M = grid[0].length;
const visit = new Array(N).fill(0).map((_) => new Array(M));
function dfs(x, y) {
visit[x][y] = 1;
for (let i = 0; i < 4; i++) {
let nx = x + dx[i],
ny = y + dy[i];
if (0 <= nx && nx < N && 0 <= ny && ny < M) {
if (!visit[nx][ny] && grid[nx][ny] === "1") {
dfs(nx, ny);
}
}
}
}
let ans = 0;
for (let x = 0; x < grid.length; x++) {
for (let y = 0; y < grid[0].length; y++) {
if (!visit[x][y] && grid[x][y] === "1") {
dfs(x, y);
ans++;
}
}
}
return ans;
};
const grid = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"],
];
console.log(numIslands(grid));
๋ฐ์ํ
'๐ algorithm > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode 1094 - Car Pooling (Medium) (0) | 2021.03.02 |
---|---|
LeetCode 49 - Group Anagrams (Medium) (0) | 2021.03.02 |
LeetCode 64 - Minimum Path Sum (Medium) (0) | 2021.03.02 |
LeetCode 55 - Jump Game (Medium) (0) | 2021.03.02 |
LeetCode 70 - Climing Stairs (Easy) (0) | 2021.03.02 |
๐ฌ ๋๊ธ