1st round, 200 number of isalnds
来源:互联网 发布:算法设计与分析吕国英 编辑:程序博客网 时间:2024/06/05 23:52
这道题是加深我对 dfs 的理解。。。对方向这个词的理解不再是停滞在树的各个分叉上,而是在二维空间的变化上。。。那么既然是二维空间,那就要有xy两个参数,base case的返回条件也就要相应确定。。。
基本思路:从左上顶点出发,扫一遍matrix,遇到1则停下来,island++,加一之后,要把这个点相连的所有土地归零,才可以在以后的技术中不重复计算!!
代码如下:
public class Solution { public int numIslands(char[][] grid) { if(grid==null || 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'){ // found an island count++; shrink(grid, i, j); } } } return count; } // when find an island, shrink the rest by setting itself and the connected spot from 1 to 0. Using dfs to check to 4 directions private void shrink(char[][] grid, int x, int y){ if( x<0 || x>=grid.length || y<0 || y>=grid[0].length || grid[x][y]!='1' ) return; grid[x][y]='0'; shrink(grid, x-1, y); shrink(grid, x+1, y); shrink(grid, x, y-1); shrink(grid, x, y+1); }}
0 0
- 1st round, 200 number of isalnds
- 1st round, 17 Letter Combinations of a Phone Number
- 1st round, 283 moveZeroes
- 1st round, 325 maxSubArrayLen
- 1st round, 314 binaryTreeVerticalTraversal
- 1st round, 78 Subsets
- "Introduction to the Theory of Computation" 1st round done ROUGHLY
- 1st round, 236 Lowest Common Ancestor of a Binary Tree
- 88.You need to calculate the number of days from 1st January 2007 till date.
- 1st homework of OS
- 1st day of MySql
- 1st round, 1 2Sum
- 1st round, 311 Sparse Matrix Multiplication
- 1st round, 67 Add Binary
- 1st round: 278 First Bad Version
- 1st round, 253 Meeting Rooms II
- 1st round, 91 Decode Ways
- 1st round, 15 3Sum
- UNIX网络编程卷一 第一章 简介
- 怎样设计合适的接口
- hive拉链表和增量表
- Video4Linux框架简介(5) - 控制框架
- postgres拷贝指定数据
- 1st round, 200 number of isalnds
- Android开发自定义水印图片
- android 利用ViewDragHelper实现childView可随手指移动的自定义ViewGroup
- char *指向的内容不可修改
- WinSocket实现进程通信的一个简单实例
- mvc result之JavaScriptResult
- 如何通过sql语句查看数据库的大小
- 闭锁之CountDownLatch(java并发编程实战5.5.1)
- aaa