https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e?tpId=196&tqId=37167&ru=/exam/oj
dfs
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 判断岛屿数量
* @param grid char字符型vector<vectovecr<>>
* @return int整型
*/
vector<vector<int>> vv; // 记录是否被遍历过
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int m, n;
int solve(vector<vector<char> >& grid) {
// write code here
m = grid.size();
n = grid[0].size();
vv.assign(m, vector<int>(n, 0));
int ret = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1' && !vv[i][j]) {
//cout << i << " " << j << endl;
dfs(grid, i, j);
ret++;
}
}
}
return ret;
}
void dfs(vector<vector<char> >& grid, int i, int j) {
for (int k = 0; k < 4; ++k) {
int a = i + dx[k], b = j + dy[k];
if (a >= 0 && a < m && b >= 0 && b < n && grid[a][b] == '1' && !vv[a][b]) {
//cout << a << " " << b << endl;
vv[a][b] = 1;
dfs(grid, a, b);
}
}
}
};
bfs:
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 判断岛屿数量
* @param grid char字符型vector<vector<>>
* @return int整型
*/
int n, m;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
vector<vector<bool>> vv;
int solve(vector<vector<char> >& grid) {
// write code here
m = grid.size(), n = grid[0].size();
vv.assign(m, vector<bool>(n, false));
int ret = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1' && !vv[i][j]) {
//cout << i << " " << j << endl;
bfs(grid, i, j);
ret++;
}
}
}
return ret;
}
void bfs(vector<vector<char> >& grid, int i, int j) {
queue<pair<int, int>> q;
q.push({i, j});
vv[i][j] = true;
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
for (int k = 0; k < 4; ++k) {
int a = x + dx[k], b = y + dy[k];
if (a >= 0 && a < m && b >= 0 && b < n && grid[a][b] == '1' && !vv[a][b]) {
q.push({a, b});
vv[a][b] = true;
}
}
}
}
};