-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find_number_of_island.cpp
89 lines (79 loc) · 2.13 KB
/
Find_number_of_island.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
79
80
81
82
83
84
85
86
87
88
89
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
// Function to find the number of islands.
void bfs(int row, int col, vector<vector<int>> &vis, vector<vector<char>> &grid)
{
int n = grid.size();
int m = grid[0].size();
vis[row][col] = 1;
queue<pair<int, int>> q;
q.push({row, col});
while (!q.empty())
{
int row = q.front().first;
int col = q.front().second;
q.pop();
for (int delrow = -1; delrow <= 1; delrow++)
{
for (int delcol = -1; delcol <= 1; delcol++)
{
int nrow = row + delrow;
int ncol = col + delcol;
if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && grid[nrow][ncol] == '1' && !vis[nrow][ncol])
{
vis[nrow][ncol] = 1;
q.push({nrow, ncol});
}
}
}
}
}
int numIslands(vector<vector<char>> &grid)
{
int n = grid.size();
int m = grid[0].size();
vector<vector<int>> vis(n, vector<int>(m, 0));
int cnt = 0;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < m; col++)
{
if (!vis[row][col] && grid[row][col] == '1')
{
cnt++;
bfs(row, col, vis, grid);
}
}
}
return cnt;
}
};
//{ 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