您的位置:首页 > 其它

LeetCode--200. Number of Islands

2016-03-04 20:08 330 查看
Problem:

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:

11110

11010

11000

00000

Answer: 1

Example 2:

11000

11000

00100

00011

Answer: 3

Analysis:

这个题是典型的DFS的题,可以轮询每一个数字,看起相邻的相连的是否为1 ,如果是1 则说明是一个岛,

做这个题我反复提交了好几次,主要注意以下几点:

考虑input为一元数组或者空的情况

考虑边界条件,注意在数组范围内,一定横坐标边界卡定为length

利用visited[][]二维数组做访问标记,减少计算次数。

Answer:

public class Solution {
public int numIslands(char[][] grid) {
if (grid==null || grid.length==0 || grid[0].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]) {
dfs(i,j,grid,visited);
res++;
}
}
}
return res;
}

public void dfs(int i,int j,char[][] grid,boolean[][] visited){
if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || visited[i][j] || grid[i][j]=='0') return;
visited[i][j]=true;
dfs(i-1,j,grid,visited);
dfs(i+1,j,grid,visited);
dfs(i,j-1,grid,visited);
dfs(i,j+1,grid,visited);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: