首页 > 其他 > 详细

Leetcode 200. number of Islands

时间:2016-11-17 09:57:51      阅读:113      评论:0      收藏:0      [点我收藏+]

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或者BFS都可以。

Solution. 1 DFS.

 1 class Solution(object):
 2 
 3     def numIslands(self, grid):
 4         """
 5         :type grid: List[List[str]]
 6         :rtype: int
 7         """
 8         m = len(grid)
 9         if m == 0:
10             return 0
11         n = len(grid[0])
12         
13         ans = 0
14         for i in range(m):
15             for j in range(n):
16                 if grid[i][j] == 1:
17                     ans += 1
18                     self.helper(grid, m, n, i, j)
19                 
20         return ans
21         
22     def helper(self, grid, m, n, i, j):
23         if (i < 0 or j < 0 or i > m-1 or j > n-1):
24             return 
25         
26         if grid[i][j] == 1:
27             grid[i][j] = 2
28             self.helper(grid, m, n, i-1, j)
29             self.helper(grid, m, n, i+1, j )
30             self.helper(grid, m, n, i, j-1)
31             self.helper(grid, m, n, i, j+1)

Solution. 2 BFS

 1 class Solution(object):
 2     def numIslands(self, grid):
 3         """
 4         :type grid: List[List[str]]
 5         :rtype: int
 6         """
 7         m = len(grid)
 8         if m == 0:
 9             return 0
10         n = len(grid[0])
11         visited = [ [False]* n for x in range(m)]
12         ans = 0
13         for i in range(m):
14             for j in range(n):
15                 if grid[i][j] == 1 and visited[i][j] == False:
16                     ans += 1
17                     self.bfs(grid, visited, m, n, i, j)
18                 
19         return ans
20         
21     def bfs(self, grid, visited, m, n, i, j):
22         direct = [[0,1],[0,-1],[1,0],[-1,0]]
23         queue = [[i, j]]
24         visited[i][j] = True
25         
26         while queue:
27             front = queue.pop(0)
28             for p in direct:
29                 np = [front[0]+p[0], front[1]+p[1]]
30                 if self.isValid(np, m, n) and grid[np[0]][np[1]] == 131                 and visited[np[0]][np[1]] == False:
32                     visited[np[0]][np[1]] = True
33                     queue.append(np)
34     
35     def isValid(self, np, m, n):
36         return np[0]>=0 and np[0]<m and np[1]>=0 and np[1]<n

 

Leetcode 200. number of Islands

原文:http://www.cnblogs.com/lettuan/p/6072378.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!