【LeetCode】Number of Islands
2015-06-02 09:28
387 查看
Number of Islands
Total Accepted: 8945 Total Submissions: 41107 My Submissions Question Solution
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:
Answer: 1
Example 2:
Answer: 3
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
【解题思路】
1、题目大意为,1代表岛屿,2代表水。如果岛屿水平或者垂直相连,算一个岛。求所给的二次矩阵中岛屿的个数。
2、典型BFS,遍历每一个点,判断其相邻的点是否为1,如果为1即认为是同一个岛。
3、遍历结束,count的个数即为岛屿的个数。
Java AC
Total Accepted: 8945 Total Submissions: 41107 My Submissions Question Solution
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
【解题思路】
1、题目大意为,1代表岛屿,2代表水。如果岛屿水平或者垂直相连,算一个岛。求所给的二次矩阵中岛屿的个数。
2、典型BFS,遍历每一个点,判断其相邻的点是否为1,如果为1即认为是同一个岛。
3、遍历结束,count的个数即为岛屿的个数。
Java AC
public class Solution { private int stepArr[][] = {{0,1},{0,-1},{1,0},{-1,0}}; private int visit[][]; private int m, n; public int numIslands(char[][] grid) { if(grid == null || grid.length == 0){ return 0; } int count = 0; m = grid.length; n = grid[0].length; visit = new int[m] ; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == '1' && visit[i][j] == 0){ bfs(grid, i, j); count++; } } } return count; } private void bfs(char grid[][], int i, int j){ Queue<Integer> queue = new LinkedList<Integer>(); queue.add(i * n + j); while(!queue.isEmpty()){ int num = queue.poll(); int x = num / n; int y = num % n; for(int k = 0; k < 4; k++){ int newX = x + stepArr[k][0]; int newY = y + stepArr[k][1]; if(newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == '1' && visit[newX][newY] == 0 ){ queue.add(newX * n + newY); visit[newX][newY] = 1; } } } } }
相关文章推荐
- EXTJS4 创建panel,deferredRender : false,
- 去除discuz 的面包屑导航里的分区导航
- 梁思成:有所专而又多能,精于一而又博学
- 2014最新苹果开发者账号注册流程图解分享
- 假日1737棋牌源码加几款精品游戏源码,附带数据库完整下载
- ArcGIS对未知坐标系要素建立拓扑查错修错
- No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386).
- 使用common-fileupload实现文件上传
- iOS - 版面实现记录二
- 学习:二维码、QR码、J4L-QRCode、java
- vlc-android 获取MediaPlayerEncounteredError,MediaPlayerBuffering等各种事件的响应
- ofstream和ifstream详细用法
- rstudio server包的安装位置
- 安卓自定义日期控件(仿QQ,IOS7)续
- iOS - 版面实现记录一
- win+r 快捷
- 陈怡暖:2015.6.2拥有精准策略,杜绝优柔寡断(早评)
- 深入理解RunLoop
- Netty的并发编程实践5:不要依赖线程优先级
- 新版福昕阅读器(Foxit Reader)启动速度慢解决办法