题目:200. 岛屿数量 - 力扣(LeetCode)
题解:是一个非常裸的Floodfill问题来求解连通块个数,那么可以想到使用DFS或者BFS来遍历解决。当该点为1时,即对上下左右四个位置遍历,直到周围全为‘0’点。
class Solution {
public:const int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};void bfs(vector<vector<char>>& grid,int x, int y, const int n, const int m){queue<pair<int,int>> q;q.push({x, y});while(q.size()){auto t = q.front();q.pop();for(int i = 0; i < 4; i ++){int x = t.first + dir[i][0];int y = t.second + dir[i][1];if(x < 0 || x >= n || y < 0 || y >= m) continue;if(grid[x][y] == '0') continue;grid[x][y] = '0';q.push({x, y});}}}int numIslands(vector<vector<char>>& grid) {vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};const int n = grid.size();const int m = grid[0].size();int ans = 0;for(int i = 0; i < n; i ++)for(int j = 0; j < m; j ++)if(grid[i][j] == '1'){bfs(grid, i, j,n, m);ans ++;}return ans;}
};