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.
假设给了2维的网格图(包含“0”和“1”,1代表陆地,0代表水),计算出有多少岛。岛被水围绕并陆地在垂直或者水平方向连接,假设网格的四边被水围绕。
【分析】
1. 设置一个辅助的二维数组boolean visited[][],用于记录当前点是否访问过,false代表没访问过,true代表访问过
2. 采用DFS的方式
【算法实现】
public class Solution { public int numIslands(char[][] grid) { if(grid==null || grid.length==0) return 0; boolean[][] visited = new boolean[grid.length][grid[0].length]; int res=0; for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[0].length; j++) { if(grid[i][j]=='1' && !visited[i][j]) { System.out.println("i:"+i+",j:"+j); res++; visited[i][j]=true; randomMove(grid,i,j,visited); } } } return res; } public static void randomMove(char[][] grid,int x,int y,boolean[][] visited) { int rows = grid.length; int cols = grid[0].length; int[][] pos = {{0,1},{0,-1},{-1,0},{1,0}}; for(int i=0; i<4; i++) { int xx = x+pos[i][0]; int yy = y+pos[i][1]; if(xx>=0 && xx<rows && yy>=0 && yy<cols && !visited[xx][yy] && grid[xx][yy]=='1') { visited[xx][yy] = true; randomMove(grid , xx , yy , visited); } } } }