-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxAreaofIsland.cpp
More file actions
49 lines (38 loc) · 1.84 KB
/
MaxAreaofIsland.cpp
File metadata and controls
49 lines (38 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
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.
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.
https://leetcode.com/explore/challenge/card/june-leetcoding-challenge-2021/603/week-1-june-1st-june-7th/3764/
*/
class Solution {
public:
int sizeOfIsland(vector<vector<int>> &grid, vector<vector<int>> &visited, int i, int j){
if (i < 0 || (i > grid.size()-1) || j < 0 || (j > grid[0].size()-1) || grid[i][j] == 0 || visited[i][j] == 1){
return 0;
}
visited[i][j] = 1;
return (1 + sizeOfIsland(grid, visited, i+1, j) + sizeOfIsland(grid, visited, i-1, j) + sizeOfIsland(grid, visited, i, j+1) + sizeOfIsland(grid, visited, i, j-1));
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int i, j, res=0;
vector<vector<int>> visited(grid.size(), vector<int>(grid[0].size(), 0));
for(i=0; i<grid.size(); i++){
for(j=0; j<grid[0].size(); j++){
if(visited[i][j]==0 || grid[i][j] == 1)
res = max(res, sizeOfIsland(grid, visited, i, j));
}
}
return res;
}
};