标签:val ace als app i+1 dfs self front call
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]] == ‘1‘31 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
标签:val ace als app i+1 dfs self front call
原文地址:http://www.cnblogs.com/lettuan/p/6072378.html