-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
200.Number_of_Islands.cpp
47 lines (32 loc) · 1.03 KB
/
200.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
42
43
44
45
46
47
// Solution to the Problem : Number Of Islands
// https://leetcode.com/problems/number-of-islands/
class Solution {
public:
void checkIslands(vector<vector<char>>&grid,int i,int j,int m,int n){
if(i<0||j<0||i>=m||j>=n||grid[i][j]!='1'){
return;
}
grid[i][j] = '2';
checkIslands(grid,i-1,j,m,n);
checkIslands(grid,i,j-1,m,n);
checkIslands(grid,i+1,j,m,n);
checkIslands(grid,i,j+1,m,n);
}
int countIslands(vector<vector<char>> &grid){
int m = grid.size();
int n = grid[0].size();
int count = 0;
for(int i = 0 ; i < m ;i++){
for(int j = 0 ;j < n ;j++){
if(grid[i][j]=='1'){
count++;
checkIslands(grid,i,j,m,n);
}
}
}
return count;
}
int numIslands(vector<vector<char>>& grid) {
return countIslands(grid);
}
};