-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.cpp
59 lines (54 loc) · 1.27 KB
/
Solution.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
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <deque>
#include <unordered_map>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
/// Nobody can code out his code without consistent learning
class Solution {
public:
int m;
int n;
int cnt;
vector<vector<char>> g;
void traverse(int i, int j) {
g[i][j] = '0';
if (i > 0 and g[i - 1][j] == '1')
traverse(i - 1, j);
if (i < m - 1 and g[i + 1][j] == '1')
traverse(i + 1, j);
if (j > 0 and g[i][j - 1] == '1')
traverse(i, j - 1);
if (j < n - 1 and g[i][j + 1] == '1')
traverse(i, j + 1);
}
int numIslands(vector<vector<char>>& grid) {
m = grid.size();
if (m == 0) return 0;
n = grid[0].size();
if (n == 0) return 0;
cnt = 0;
g.clear();
for (auto & i : grid)
g.push_back(i);
for (int i = 0; i < m; i ++ ) {
for (int j = 0; j < n; j ++ ) {
if (g[i][j] == '1') {
cnt ++ ;
traverse(i, j);
}
}
}
return cnt;
}
};
int main() {
Solution a;
return 0;
}