给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
这个题还是用DFS进行遍历,遇到1且没有遍历过就搜索它周围所有的1。
C++源代码:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.empty() || grid[0].empty()) return 0;
int m = grid.size(), n = grid[0].size(), res=0;
vector<vector<bool>> visited(m, vector<bool>(n, false));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]=='1' && !visited[i][j]){
DFS(grid, visited, i, j);
res++;
}
}
}
return res;
}
void DFS(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y){
if(x<0 || x>=grid.size()) return;
if(y<0 || y>=grid[0].size()) return;
if(grid[x][y]!='1' || visited[x][y]) return;
visited[x][y]=true;
DFS(grid, visited, x-1, y);
DFS(grid, visited, x+1, y);
DFS(grid, visited, x, y-1);
DFS(grid, visited, x, y+1);
}
};
python3源代码:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if len(grid)==0 or len(grid[0])==0:
return 0
m = len(grid)
n = len(grid[0])
res = 0
visited = [[0 for i in range(n)] for j in range(m)]
for i in range(m):
for j in range(n):
if grid[i][j]=='1' and visited[i][j]==0:
self.DFS(grid, visited, i, j)
res += 1
return res
def DFS(self, grid, visited, x, y):
if x<0 or x>=len(grid): return
if y<0 or y>=len(grid[0]): return
if grid[x][y]!='1' or visited[x][y]==1: return
visited[x][y] = 1
self.DFS(grid, visited, x+1, y)
self.DFS(grid, visited, x-1, y)
self.DFS(grid, visited, x, y+1)
self.DFS(grid, visited, x, y-1)