基于bfs搜索方法。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.empty())
return 0;
int counts_ = 0;
int width_ = grid.size();
int length_ = grid[0].size();
for (int i = 0; i < width_; i++) {
for (int j = 0; j < length_; j++) {
// 检查节点值
if (grid[i][j] == '0')
continue;
// 对当前节点进行广度优先搜索
queue<pair<int, int>> q_;
q_.push(pair<int, int>(i, j));
grid[i][j] = '0';
while (q_.size()) {
pair<int, int> n_ = q_.front();
// 上
if (n_.first > 0 && grid[n_.first - 1][n_.second] == '1') {
q_.push(pair<int, int>(n_.first - 1, n_.second));
grid[n_.first - 1][n_.second] = '0';
}
// 下
if (n_.first + 1 < width_ && grid[n_.first + 1][n_.second] == '1') {
q_.push(pair<int, int>(n_.first + 1, n_.second));
grid[n_.first + 1][n_.second] = '0';
}
// 左
if (n_.second > 0 && grid[n_.first][n_.second - 1] == '1') {
q_.push(pair<int, int>(n_.first, n_.second - 1));
grid[n_.first][n_.second - 1] = '0';
}
// 右
if (n_.second + 1 < length_ && grid[n_.first][n_.second + 1] == '1') {
q_.push(pair<int, int>(n_.first, n_.second + 1));
grid[n_.first][n_.second + 1] = '0';
}
q_.pop();
}
counts_++;
}
}
return counts_;
}
};