Leetcode 200:Number of Island

题目: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.

例子:

11000
11000
00100
00011

输出结果:3个小岛。

答案:

public class NumberofIslands {
	static int[] dx = {-1,0,0,1};
	static int[] dy = {0,1,-1,0};
	public static int numIslands(char[][] grid) {
		if(grid==null || grid.length==0) return 0;
		int islands = 0;
		for(int i=0;i<grid.length;i++) {
			for(int j=0;j<grid[i].length;j++) {
				if(grid[i][j]=='1') {
					explore(grid,i,j);
					islands++;
				}
			}
		}
		return islands;
	}
	public static void explore(char[][] grid, int i, int j) {
		grid[i][j]='x';
		for(int d=0;d<dx.length;d++) {
			if(i+dy[d]<grid.length && i+dy[d]>=0 && j+dx[d]<grid[0].length && j+dx[d]>=0 && grid[i+dy[d]][j+dx[d]]=='1') {
				explore(grid,i+dy[d],j+dx[d]);
			}
		}
	}
}
解题思路:
  1. Scan each cell in the grid.
  2. If the cell value is ‘1’ explore that island.
  3. Mark the explored island cells with ‘x’.
  4. Once finished exploring that island, increment islands counter.(注:本博客答案来自LeetCode Discuss 作者——fabrizio3)

猜你喜欢

转载自blog.csdn.net/lxs1995/article/details/79608479