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.

Input:
11110
11010
11000
00000 Output: 1
Input:
11000
11000
00100
00011 Output: 3

思路:

- DFS and flip the bit-1 on the grid to 0 as we go: to 4 different directions
- Loop through all positions
- Visited spots won't be visited again because they are updated to '0'

怎样check 当前这格是否被visited过?

1.开一个boolean[][]  sized as the original input matrix.  但需要额外空间

2.directly flag ‘2’ or ‘0’ (any char excpet ‘1’) in the original input matrix  插个小旗flag一下

相关小岛题变种

[leetcode]694. Number of Distinct Islands你究竟有几个异小岛?

代码:

class Solution {
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[i].length;j++) {
if (grid[i][j]=='1') {
count++;
helper(grid, i, j);
}
}
} return count;
} private void helper(char[][] grid, int i, int j) {
if ((i<0) || (j<0) || (i>=grid.length) || (j>=grid[0].length)
|| grid[i][j] != '1' ) return; grid[i][j] = '0'; // mark visited spot
helper(grid, i+1, j);
helper(grid, i-1, j);
helper(grid, i, j+1);
helper(grid, i, j-1);
}
}

最新文章

  1. [Python基础知识]正则
  2. Windows消息机制知识点总结
  3. Customer IEnuramble Extension
  4. Java 8 VM GC Tuning Guide Charter2
  5. ajax_for example
  6. Linux内存寻址之分页机制
  7. js 实现关键词球状旋转效果
  8. SDWebImage 官方文档
  9. Swift 可选类型-备
  10. LCT
  11. redis 系列15 数据对象的(类型检查,内存回收,对象共享)和数据库切换
  12. 实现两线程的同步二(lockSupport的park/unpark)
  13. cmake使用示例与整理总结
  14. Asp.Net WebAPI及相关技术介绍(含PPT下载)
  15. Renesas M16C/6X -- Simple PWM Signal Generation Using DMA
  16. python object对象
  17. vue-cli 知识点
  18. jQuery1.7版本之后的on方法
  19. Jekins - Hello world,Jekins + Maven + Git + Tomcat 的简单应用
  20. OpenStack高可用方案及配置

热门文章

  1. Xamarin Android 下拉列表
  2. 【SpringBoot】搜索框架ElasticSearch介绍和整合SpringBoot
  3. C# winform 打开主界面并关闭登录界面
  4. html5-websocket实现基于远程方法调用的数据交互
  5. ionic3 热更新发布步骤记录
  6. k8s Nodeport方式下service访问,iptables处理逻辑(转)
  7. MySQL数据库的库表基本操作
  8. oracle入坑日记&lt;一&gt; 安装
  9. Android 开发 HandlerThread详解 转载
  10. Android 开发 框架系列 EventBus 事件总线