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(四叉树,上下左右) +剪枝

剪枝是剪掉遍历过的结点

class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
count=0
m=len(grid)
if m==0:
return 0
n=len(grid[0])
#visit=[[False]*n]*m
visit = [[False for i in range(n)]for j in range(m)]
def check(x, y):
if x >= 0 and x<m and y>= 0 and y< n and grid[x][y] == '1' and visit[x][y] == False:
return True
def dfs(i ,j):
nbrow = [1,0,-1,0]
nbcol = [0,1,0,-1]
for d in range(4):
ni=i+nbrow[d]
nj=j+nbcol[d]
if(check(ni,nj)==True):
visit[ni][nj]=True
dfs(ni,nj)
for i in range(m):
for j in range(n):
if(check(i,j)==True):
visit[i][j]=True
dfs(i,j)
count+=1
return count

  

最新文章

  1. paxos(chubby) vs zab(Zookeeper)
  2. cocos2dx 入门
  3. ACEXML解析XML文件&mdash;&mdash;我是如何学习并在短时间内掌握一个库的使用方法的
  4. find用法
  5. 嵌入式开发笔记 - U-Boot相关
  6. MATLAB中如何使用遗传算法
  7. 如何在cocos2d项目中enable ARC
  8. Mysql笔记5之查询
  9. 解决maven 下载 hadoop-client 客户端 报错的问题
  10. 源码阅读之mongoengine(0)
  11. 使用FileReader实现前端预览所选图片
  12. ELK学习总结(1-3)倒排索引
  13. python笔记--2--字符串、正则表达式
  14. PHP面向对象的小总结
  15. ThinkPHP 5 验证码
  16. Haproxy 安装初体验
  17. jmeter打开图形化界面时指定代理
  18. Java中的 内部类(吐血总结)
  19. 【Android】GPS定位基本原理浅析
  20. python 拷贝 深拷贝 浅拷贝 赋值

热门文章

  1. Windows 10 远程连接出现函数错误 【这可能由于CredSSP加密Oracle修正】
  2. Excel自定义公式,类似VLOOKUP的查询
  3. Centos7上搭建redis主从
  4. 浅析C#中new、override、virtual关键字的区别
  5. objective-c高级编程 笔记
  6. 文本相似度 — TF-IDF和BM25算法
  7. codeforces div2 220 解题
  8. jQuery 中的事件绑定
  9. Python学习案例之Web版语音合成播报
  10. java事件监听机制