[LeetCode 200] Number of Islands
2015-09-13 13:31
525 查看
Given a 2d grid map of
are all surrounded by water.
Example 1:
Answer: 1
Example 2:
Answer: 3
solution:
DFS + pruning
found 1 then search its up, left, down, right. Meanwhile change value to 2, pruning.
'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
solution:
DFS + pruning
found 1 then search its up, left, down, right. Meanwhile change value to 2, pruning.
public int numIslands(char[][] grid) { int res = 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'){ res++; populateAdj(grid, i, j); } } } return res; } public void populateAdj(char[][] grid, int x, int y){ if(x>= grid.length || y>=grid[0].length || x<0 || y<0) return; if(grid[x][y] == '1') { grid[x][y] = '2'; populateAdj(grid, x-1, y); populateAdj(grid, x+1, y); populateAdj(grid, x, y-1); populateAdj(grid, x, y+1); } }
相关文章推荐
- Angular.js 与script.js 异步加载
- 天天团购系统-简单的目录结构
- java-接口List-Map
- mysql --设置root 密码
- Memcached 源码安装 与 配置
- lintcode-数字组合-135
- 关于函数返回值为引用和指针的问题
- 1.2交叉工具链
- Linux内核编程的特点
- GBK和UTF8的区别,该选择哪个版本
- 1、windows下开放热点,及查找连接上的客户IP
- MVCC实现-MYSQL INNODB MVCC实现
- Javascript继承(暂略去中转函数、组合继承和寄生继承)
- Nginx学习笔记一_UNIX中的IO模型
- Unbuntu12.04 x64 安装jdk-7u45-linux-x64.tar.gz
- Leetcode: Reverse Words in a String
- jtagger Versatile multiprogrammer for FPGAs, MCUs, etc.
- “状态机”学习笔记
- 陈越、何钦铭《数据结构》第二讲线性结构 笔记
- 你应该知道的最好Webmail邮件客户端