-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfIslands.cpp
More file actions
80 lines (66 loc) · 1.59 KB
/
NumberOfIslands.cpp
File metadata and controls
80 lines (66 loc) · 1.59 KB
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
#include<bits/stdc++.h>
using namespace std;
void bfs(int row,int col,vector<vector<int>>&vis,vector<vector<char>>&grid)
{
vis[row][col]=1;
queue<pair<int,int>>q;
q.push({row,col});
int n = grid.size();
int m = grid[0].size();
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 && !vis[nrow][ncol] && grid[nrow][ncol]=='1')
{
vis[nrow][ncol]=1;
q.push({nrow,ncol});
}
}
}
}
}
int NumOfIsland(vector<vector<char>>&grid)
{
int n = grid.size();
int m = grid[0].size();
int count = 0;
vector<vector<int>>vis(n,vector<int>(m,0));
for(int row=0;row<n;row++)
{
for(int col=0;col<m;col++)
{
if(!vis[row][col] && grid[row][col]=='1')
{
count++;
bfs(row,col,vis,grid);
}
}
}
return count;
}
int main()
{
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];
}
}
int ans = NumOfIsland(grid);
cout<<ans;
}
// Complexity Analysis
// Space Complexity -> O(N^2)+O(N^2)
// Time Complexity -> O(N^2) + O(N^2) ~ O(N^2)