문제
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.
입출력
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.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
제약
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 50
- grid[i][j] is either 0 or 1.
코드
var area;
var maxAreaOfIsland = function(grid) {
let maxArea = 0;
for(let i=0; i<grid.length; i++) {
for(let j=0; j!=-1 && j<=grid[0].length;) {
area = 0;
j = (j===0) ? grid[i].indexOf(1) : grid[i].indexOf(1, j+1);
if(grid[i][j]==1) {
isConnected(i, j, grid);
if(area > maxArea) maxArea = area;
}
}
}
return maxArea;
};
function isConnected(row, col, grid) {
grid[row][col] = -1;
area++;
if(row-1>=0 && grid[row-1][col]==1) isConnected(row-1, col, grid);
if(row+1<grid.length && grid[row+1][col]==1) isConnected(row+1, col, grid);
if(col-1>=0 && grid[row][col-1]==1) isConnected(row, col-1, grid);
if(col+1<grid[0].length && grid[row][col+1]==1) isConnected(row, col+1, grid);
}
'Coding > LeetCode' 카테고리의 다른 글
[LeetCode/JavaScript] 58. Length of Last Word (easy) (0) | 2021.11.03 |
---|---|
[LeetCode/JavaScript] 11. Container With Most Water (medium) (0) | 2021.10.07 |
[LeetCode/JavaScript] 733. Flood Fill (easy) (0) | 2021.09.21 |
[LeetCode/JavaScript] 3. Longest Substring Without Repeating Characters (medium) (0) | 2021.09.21 |
[LeetCode/JavaScript] 876. Middle of the Linked List (easy) (0) | 2021.09.21 |