leetcode [200]Number of Islands
Given a 2d grid map of '1'
s (land) and '0'
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
题目大意:
有一个二维的地图,地图中1代表着陆地,0代表水,如果四周完全被水围住,那么这就是一个岛,计算地图中岛的个数。
解法:
这一道题目,我借鉴了之前leetcode[130]https://www.cnblogs.com/xiaobaituyun/p/10715812.html的思想,首先将地图中边缘的岛进行统计,并且在统计完成之后,将地图设置为‘0’。
然后再统计地图中不靠边缘的岛。
class Solution { int count=0; void dfs(char[][] grid,int i,int j){ if(grid[i][j]=='0') return; grid[i][j]='0'; if(i+1<grid.length) dfs(grid,i+1,j); if(j+1<grid[0].length) dfs(grid,i,j+1); if(i-1>=0) dfs(grid,i-1,j); if(j-1>=0) dfs(grid,i,j-1); } public int numIslands(char[][] grid) { if(grid.length==0||grid[0].length==0) return 0; int m=grid.length; int n=grid[0].length; for(int i=0;i<m;i++) { if (grid[i][0] == '1') { count++; dfs(grid, i, 0); } } for(int i=0;i<m;i++){ if(grid[i][n-1]=='1') { count++; dfs(grid, i, n - 1); } } for(int i=0;i<n;i++) { if(grid[0][i]=='1') { count++; dfs(grid, 0, i); } } for(int i=0;i<n;i++){ if(grid[m-1][i]=='1'){ count++; dfs(grid,m-1,i); } } for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(grid[i][j]=='1'){ count++; dfs(grid,i,j); } } } return count; } }
代码可以简化为;
class Solution { void dfs(char[][] grid,int i,int j){ if(i<0||i>=grid.length||j<0||j>=grid[0].length||grid[i][j]=='0') return; grid[i][j]='0'; dfs(grid,i+1,j); dfs(grid,i,j+1); dfs(grid,i-1,j); dfs(grid,i,j-1); } public int numIslands(char[][] grid) { if(grid.length==0||grid[0].length==0) return 0; int m=grid.length; int n=grid[0].length; int count=0; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(grid[i][j]=='1'){ count++; dfs(grid,i,j); } } } return count; } }