forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Islands.cpp
41 lines (33 loc) · 891 Bytes
/
Number of Islands.cpp
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
// Runtime: 83 ms (Top 18.08%) | Memory: 12.3 MB (Top 54.41%)
class Solution {
public:
void calculate(vector<vector<char>>& grid, int i, int j)
{
if(i>=grid.size() || j>=grid[i].size() || i<0 || j<0)
return;
if(grid[i][j]=='0')
return;
grid[i][j] = '0';
calculate(grid,i,j-1);
calculate(grid,i-1,j);
calculate(grid,i,j+1);
calculate(grid,i+1,j);
}
int numIslands(vector<vector<char>>& grid) {
int ans = 0;
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
if(grid[i][j]=='0')
continue;
else if (grid[i][j]=='1')
{
ans++;
calculate(grid,i,j);
}
}
}
return ans;
}
};