[leetcode-200]Number of Islands(java)
2015-08-27 21:12
465 查看
问题描述:
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
分析:这道题主要考察DFS,维护一个栈,然后将相连的1全部遍历一遍之后,出栈,然后 count++;
代码如下:352ms
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
分析:这道题主要考察DFS,维护一个栈,然后将相连的1全部遍历一遍之后,出栈,然后 count++;
代码如下:352ms
[code]public class Solution { class Node{ int x; int y; public Node(int x,int y){ this.x = x; this.y = y; } } public int numIslands(char[][] grid) { Stack<Node> stack = new Stack<>(); int count = 0; int row = grid.length; if(row<=0) return 0; int col = grid[0].length; for(int i = 0;i<row;i++){ for(int j = 0;j<col;j++){ if(grid[i][j]=='1'){ stack.push(new Node(i,j)); while(!stack.isEmpty()){ Node top = stack.pop(); int x = top.x; int y = top.y; grid[x][y] = '0'; if(x+1<row && grid[x+1][y]=='1') stack.push(new Node(x+1,y)); if(x-1>=0 && grid[x-1][y]=='1') stack.push(new Node(x-1,y)); if(y+1<col && grid[x][y+1] == '1') stack.push(new Node(x,y+1)); if(y-1>=0 && grid[x][y-1] == '1') stack.push(new Node(x,y-1)); } count++; } } } return count; } }
相关文章推荐
- java Cookie详解
- Junit(1)在Eclipse中使用JUnit4进行单元测试
- JAVA模板 Java做acm所需要的基础知识之排序问题
- java模板 Java做acm所需要的基础知识之基本输入输出问题
- Java中测试对象的等价性
- Struts2笔记——struts常用标签
- Struts2笔记——struts常用标签
- [JNI] java.lang.UnsatisfiedLinkError:Native method not found && no implementation found for native ~
- springMVC(3) 给界面传递数据
- spring mvc 异常统一处理方式
- 【Java】获取此次请求URL,获取服务器根路径
- [java多线程] - Thread&Runnable运用
- java.lang.OutOfMemoryError: PermGen space
- java 多线程(三)条件对象
- java中栈和堆的区别
- Java IO编程 学习笔记 (其一:基础部分)
- java的4种代码块
- java多线程(二)锁对象
- java多线程(一)Race Condition现象及产生的原因
- Java基于数组和循环实现的控制台五子棋