[JS] Max Area of Island

2022. 7. 27. 01:19

🔒 문제 (LeetCode 695)

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with a value 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1.

 

🌊 입출력

Example 1:

Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.

 


 

🔑 해결

🌌 알고리즘 - DFS

/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxAreaOfIsland = function(grid) {
    let answer = 0;
    const m = grid.length;
    const n = grid[0].length;
    
    function dfs(r, c) {  
        if(r < 0 || r >= m || c < 0 || c >= n || !grid[r][c]) return 0;
        grid[r][c] = 0;

        return 1 + dfs(r+1, c) + dfs(r, c+1) + dfs(r-1, c) + dfs(r, c-1);
    }
    
    for(let i = 0; i < m; i++) {
        for(let j = 0; j < n; j++) {
            if(grid[i][j]) answer = Math.max(answer, dfs(i, j));
        }
    }
    
    return answer;
};

'코딩테스트 (JS) > DFS | BFS' 카테고리의 다른 글

[JS] Merge Two Binary Trees  (0) 2022.07.29
[JS] Flood Fill  (0) 2022.07.29
[JS] 양과 늑대  (0) 2022.07.07
[JS] 모두 0으로 만들기  (0) 2022.07.02
[JS] 빛의 경로 사이클  (0) 2022.06.26

+ Recent posts