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:
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); } }
相关文章推荐
- 理论与实际相结合——三层架构解析
- SPRING IN ACTION 第4版笔记-第六章Rendering web views-001- Spring支持的View Resolver、InternalResourceViewResolver、JstlView
- 校园网&openwrt记(十)iproute2
- Java学习笔记之对象与类
- URL 格式
- nodejs小问题:express不是内部或外部命令
- 判断是否是IE浏览器
- 计算机组成原理与汇编语言学习笔记(1)
- linux常用命令-ls
- getAttribute和getParameter的区别
- React-Native 如何将图片作为页面的背景以及控件的嵌套实现启动应用
- grep
- Ubuntu文件颜色的意义 ls命令 putty配色
- iOS中使用NSURLSession上传字符串
- 随机生成30道整数或者真分数组成的两位数的四则运算
- 实现一边录音一边转化为文字的功能
- 消息交互JMS(六)
- 1001. 害死人不偿命的(3n+1)猜想
- 二重积分坐标变化
- 灰度变换