-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleet200.cpp
57 lines (54 loc) · 1.27 KB
/
leet200.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
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
class Solution {
vector<vector<int>> dic = {{1,0},{-1,0},{0,1},{0,-1}};
vector<vector<bool>> visit;
int N,M;
public:
bool dfs(vector<vector<char>>& grid,int i,int j)
{
visit[i][j] = true;
for(auto v:dic)
{
int x = i+v[0];
int y = j+v[1];
if(x>=0 && y>=0 && x<N && y<M && !visit[x][y] && grid[x][y]=='1')
dfs(grid,x,y);
}
return true;
}
int numIslands(vector<vector<char>>& grid) {
N = grid.size();
M= grid[0].size();
int total = 0;
visit.resize(N);
for(int i=0;i<N;i++)
visit[i].resize(M);
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
if(grid[i][j]=='1' && !visit[i][j])
{
total += 1;
dfs(grid,i,j);
}
}
}
return total;
}
};
int main()
{
vector<vector<char>> grid = {{'1','1','1','0'},{'0','0','0','0'},{'1','0','0','0'}};
Solution sol;
int x = sol.numIslands(grid);
return 0;
}