题解 | #岛屿数量#
岛屿数量
https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
class Solution {
int counts = 0;
int visited[205][205];
int m;
int n;
int a[4] = { -1, 1, 0, 0 };
int b[4] = { 0, 0, -1, 1 };
public:
/**
* 判断岛屿数量
* @param grid char字符型vector<vector<>>
* @return int整型
*/
void dfs(int i, int j, vector<vector<char> >& grid) {
if (i > m - 1 || j > n - 1 || i < 0 || j < 0 || grid[i][j] == '0' ||
(grid[i][j] == '1' && visited[i][j] == 1)) {
return;
}
visited[i][j] = 1;
for (int k = 0; k < 4; k++) {
int newi = i + a[k];
int newj = j + b[k];
dfs(newi, newj, grid);
}
}
int solve(vector<vector<char> >& grid) {
// write code here
m = grid.size();
n = grid[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1' && visited[i][j] == 0) {
counts++;
dfs(i, j, grid);
}
}
}
return counts;
}
};