N

(Leet Code JS)Number of Islands 본문

Leet Code 알고리즘

(Leet Code JS)Number of Islands

naeunchan 2021. 11. 14. 23:56
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
반응형