-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path200.cpp
More file actions
54 lines (52 loc) · 988 Bytes
/
200.cpp
File metadata and controls
54 lines (52 loc) · 988 Bytes
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
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<bitset>
using namespace std;
class Solution {
private:
int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int m,n;
vector<vector<bool>>visited;
bool inArea(int x,int y)
{
return x>=0&&y>=0&&x<m&&y<n;
}
public:
int numIslands(vector<vector<char>>& grid) {
m=grid.size();
if(m==0)
return 0;
n=grid[0].size();
visited=vector<vector<bool>>(m,vector<bool>(n,false));
int res = 0;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(grid[i][j]=='1'&&visited[i][j]==false)
{
dfs(grid,i,j);
res++;
}
}
return res;
}
void dfs(vector<vector<char>>& grid,int x,int y)
{
visited[x][y]=true;
for(int i=0;i<4;i++)
{
int newx=x+d[i][0];
int newy=y+d[i][1];
if(inArea(newx,newy)&&visited[newx][newy]==false&&grid[newx][newy]=='1')
dfs(grid,newx,newy);
}
return;
}
};