给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] 输出:1
示例 2:
输入:grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] 输出:3
class Solution { public: //因为岛屿与岛屿之间是分割的,所以碰到陆地就变为水,便于接下来计算剩余的岛屿,直至没有岛屿 int m ,n; vector<vector<int>> direction={ {1,0},{-1,0},{0,-1},{0,1} }; void dfs(vector<vector<char>>& grid,int i,int j){ grid[i][j]='0';//将陆地变为水 for(int k=0;k<4;k++){ int x = i+direction[k][0]; int y = j+direction[k][1]; if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]=='1') dfs(grid,x,y); } } int numIslands(vector<vector<char>>& grid) { m = grid.size(); n = grid[0].size(); int res = 0; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(grid[i][j]=='1'){ dfs(grid,i,j); res++; } } } return res; } };
标签:陆地,优先,遍历,示例,int,岛屿,网格,grid From: https://www.cnblogs.com/yueshengd/p/18638594