LeetCode-Number of Islands
2016-08-15 12:19
417 查看
Given a 2d grid map of
Example 1:
Answer: 1
Example 2:
Answer: 3
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Solution:
Just BFS.
'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.
Solution:
Just BFS.
public class Solution { int[][] moves = new int[][]{{1,0},{-1,0},{0,1},{0,-1}}; public int numIslands(char[][] grid) { if (grid.length==0 || grid[0].length==0) return 0; int count = 0; for (int i=0;i<grid.length;i++) for (int j=0;j<grid[0].length;j++) if (grid[i][j] == '1'){ count++; markOneIsland(grid,new int[]{i,j}); } return count; } public void markOneIsland(char[][] grid, int[] start){ Deque<int[]> pointList = new LinkedList<int[]>(); pointList.add(start); while (!pointList.isEmpty()){ int[] head = pointList.poll(); for (int i=0;i<4;i++){ int[] next = new int[]{head[0]+moves[i][0],head[1]+moves[i][1]}; if (next[0]>=0 && next[0]<grid.length && next[1]>=0 && next[1]<grid[0].length && grid[next[0]][next[1]] == '1'){ pointList.add(next); grid[next[0]][next[1]] = '2'; } } } } }
相关文章推荐
- 就这样开始
- 杭电-1248 寒冰王座(完全背包模板)
- HDU-5835 Danganronpa(模拟水题)
- ANSI C的标准
- #497 Shape Factory
- Linux下捕捉信号
- 8.2 喀迈拉(no.1~no.10)
- 开关问题 POJ 3276 POJ 3279 POJ 1222
- openwrt编译命令make menuconfig显示错误“Your display is too small to run Menuconfig!”
- convert between RGB565 and RGB888
- 截取掉s从首字母起长度为begin的字符串
- 【算法】字符串问题相关
- 【01背包】HDU1881-毕业bg
- 总结:调用startActivityForResult,onActivityResult无响应的问题
- RS485 分时器 RS485输入模块 Modbus RTU协议
- 一般网站的Cookie控制方式
- OpenGL ES学习
- 简单实现护目镜功能
- Java Map按Value排序
- nginx、fastCGI、php-fpm关系梳理(转载参考)