-
Notifications
You must be signed in to change notification settings - Fork 30
/
Find the number of islands.cpp
78 lines (61 loc) · 1.82 KB
/
Find the 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Solution by Rahul Surana
***********************************************************
Given a grid consisting of '0's(Water) and '1's(Land). Find the number of islands.
Note: An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically or diagonally
i.e., in all 8 directions.
***********************************************************
*/
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
void dfs(int i, int j, vector<vector<char>>& grid,vector<vector<bool>>& v){
if(i>=grid.size() || j>=grid[0].size() || i< 0 || j <0 || grid[i][j] == '0') return;
if(v[i][j]) return;
v[i][j] = true;
dfs(i+1,j,grid,v);
dfs(i+1,j-1,grid,v);
dfs(i+1,j+1,grid,v);
dfs(i-1,j,grid,v);
dfs(i,j-1,grid,v);
dfs(i,j+1,grid,v);
dfs(i-1,j-1,grid,v);
dfs(i-1,j+1,grid,v);
}
int numIslands(vector<vector<char>>& grid) {
vector<vector<bool>> v(grid.size(),vector<bool>(grid[0].size(), false));
int ans = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(!v[i][j] && grid[i][j] == '1'){
dfs(i,j,grid,v);
ans++;
}
}
}
return ans;
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n, m;
cin >> n >> m;
vector<vector<char>>grid(n, vector<char>(m, '#'));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> grid[i][j];
}
}
Solution obj;
int ans = obj.numIslands(grid);
cout << ans <<'\n';
}
return 0;
} // } Driver Code Ends