给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:
[
['1','1','1','1','0'],
['1','1','0','1','0'],
['1','1','0','0','0'],
['0','0','0','0','0']
]
输出: 1
示例 2:
输入:
[
['1','1','0','0','0'],
['1','1','0','0','0'],
['0','0','1','0','0'],
['0','0','0','1','1']
]
输出: 3
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。
解法一:DFS
class Solution {
public:int numIslands(vector<vector<char>>& grid) {//记录岛屿的数量int ans = 0;for(int i = 0; i < grid.size(); ++i) {for(int j = 0; j < grid[0].size(); ++j) {if(grid[i][j] == '1') {++ans;dfs(i, j, grid);}}}return ans;}//DFSvoid dfs(int row, int col, vector<vector<char>>& grid) {//treminatorif(row < 0 || row == grid.size() || col < 0 || col == grid[0].size() || grid[row][col] == '0') return;//processgrid[row][col] = '0';//drill down//定义一个方向向量int drow[4] = {0, 0, 1, -1};int dcol[4] = {1, -1, 0, 0};for(int index = 0; index < 4; ++index) {dfs(row+drow[index], col+dcol[index], grid);}return;}
};
解法二:深度优先搜索,queue<pair<int,int>> ,pair中存放的是row,col,这个offsets定义的就很灵性!
class Solution {
public:int numIslands(vector<vector<char>>& grid) {int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0, offsets[] = {0, 1, 0, -1, 0};for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (grid[i][j] == '1') {islands++;grid[i][j] = '0';queue<pair<int, int>> todo;todo.push({i, j});while (!todo.empty()) {pair<int, int> p = todo.front();todo.pop();for (int k = 0; k < 4; k++) {int r = p.first + offsets[k], c = p.second + offsets[k + 1];if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == '1') {grid[r][c] = '0';todo.push({r, c});}}}}}}return islands;}
};