logo头像
Snippet 博客主题

【Leetcode 200】Number of Islands

难度: 中等(Medium)

题目

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

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution(object):

def depth_search(self, grid, visit, i, j):
stack = [(i,j)]
while len(stack) != 0:
(m,n) = stack.pop()
visit[m][n] = True
if m!=0 and grid[m-1][n]=='1' and visit[m-1][n]==False:
stack.append((m-1,n))
if n!=0 and grid[m][n-1]=='1' and visit[m][n-1]==False:
stack.append((m,n-1))
if m!=len(grid)-1 and grid[m+1][n]=='1' and visit[m+1][n]==False:
stack.append((m+1,n))
if n!=len(grid[0])-1 and grid[m][n+1]=='1' and visit[m][n+1]==False:
stack.append((m,n+1))

def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if grid==None or len(grid)==0:
return 0
counter = 0
visit = [[False] * len(grid[0]) for i in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]=='0' or visit[i][j]:
continue
counter += 1
self.depth_search(grid, visit, i, j)
return counter

评论系统未开启,无法评论!