-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path200. Number of Islands.cpp
87 lines (50 loc) · 1.71 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
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
class Solution
{
public:
int maxn = 0;
int numIslands(vector<vector<char>>& grid)
{
bool visit[ 600 ][ 600 ];
memset( visit, false, sizeof visit );
int dx[] = {0, 0, +1, -1};
int dy[] = {+1, -1, 0, 0};
this->maxn = grid.size() ;
int cnt = 0 ;
stack < pair <int,int> > stk ;
for(int i = 0 ; i < maxn ; i++)
{
for(int j = 0 ; j < grid[i].size() ; j++ )
{
if( visit[i][j]==false and grid[i][j]=='1' )
{
cnt++;
//cout <<"hello world"<<endl;
// this->dfs(i,j);
stk.push({i,j});
visit[i][j] = true;
while( !stk.empty() )
{
int sx = stk.top().first;
int sy = stk.top().second;
stk.pop();
for(int i = 0 ; i<4 ; i++)
{
int nowx,nowy;
nowx = sx + dx[i];
nowy = sy + dy[i];
if( nowx >= 0 and nowx < grid.size() and nowy>=0 and nowy < grid[sx].size() )
{
if( visit[nowx][nowy]==false and grid[nowx][nowy]=='1' )
{
visit[nowx][nowy] = true;
stk.push({nowx,nowy});
}
}
}
}
}
}
}
return cnt;
}
};