-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path200.cpp
More file actions
41 lines (34 loc) · 1014 Bytes
/
200.cpp
File metadata and controls
41 lines (34 loc) · 1014 Bytes
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
/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
class Solution {
void destroyIsland(vector<vector<char>>& grid, int i, int j)
{
grid[i][j] = '0';
if(i-1 >= 0 && grid[i-1][j] == '1')
destroyIsland(grid, i-1, j);
if(i+1 < grid.size() && grid[i+1][j] == '1')
destroyIsland(grid, i+1, j);
if(j-1 >= 0 && grid[i][j-1] == '1')
destroyIsland(grid, i, j-1);
if(j+1 < grid[i].size() && grid[i][j+1] == '1')
destroyIsland(grid, i, j+1);
}
public:
int numIslands(vector<vector<char>>& grid) {
int result = 0;
for(int i = 0; i < grid.size(); i++)
{
for(int j = 0; j < grid[i].size(); j++)
{
if(grid[i][j] == '1')
{
result++;
destroyIsland(grid, i, j);
}
}
}
return result;
}
};