250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code JS)Number of Islands 본문
728x90
반응형
200. Number of Islands
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is '0' or '1'.
DFS를 이용한 문제 풀이.
주어진 grid에서 "1"인 영역이면서 상하좌우로 연결된 구역의 개수를 구하면 된다.
/**
* @param {character[][]} grid
* @return {number}
*/
const numIslands = (grid) => {
let answer = 0;
const m = grid.length;
const n = grid[0].length;
const visited = Array.from({length: m}, () => Array(n).fill(false));
const directX = [-1, 1, 0, 0];
const directY = [0, 0, -1, 1];
const dfs = (x, y) => {
for(let i = 0; i < 4; i++){
const nx = x + directX[i];
const ny = y + directY[i];
if(nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] === "1" && !visited[nx][ny]){
visited[nx][ny] = true;
dfs(nx, ny);
}
}
}
for(let i = 0; i < m; i++){
for(let j = 0; j < n; j++){
if(grid[i][j] === "1" && !visited[i][j]){
answer++;
visited[i][j] = true;
dfs(i, j);
}
}
}
return answer;
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS)Rearrange Words in a Sentence (0) | 2021.11.20 |
---|---|
(Leet Code JS)Count and Say (0) | 2021.11.16 |
(Leet Code JS)Path Sum II (0) | 2021.11.14 |
(Leet Code JS)Maximum Depth of Binary Tree (0) | 2021.11.14 |
(Leet Code JS)Subdomain Visit Count (0) | 2021.11.06 |