Advertisement
jinhuang1102

200. Number of Islands

Nov 18th, 2018
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. 200. Number of Islands
  2. 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.
  3.  
  4. Input:
  5. 11110
  6. 11010
  7. 11000
  8. 00000
  9. Output: 1
  10.  
  11. 类似这种需要求出在matrix中连续字符的题,以后就都用我最会用的 BFS 的方法。先要做出一个 Visteid[][] matrix, 然后遍历每一个在matrix里面的值。如果,matrix[i][j] == "1" and visited[i][j] == 0 时,开始带入到 BFS 中。 在BFS中遍历 上下左右四个方向的值,如果符合条件就加到BFS的queue中,当queue is None, 说明找到了一个结果。然后返回继续遍历没有被visited过得值
  12.  
  13. class Solution(object):
  14.     def neighbors(self, grid, visited, x, y):
  15.         dx = [0,0,-1,1]
  16.         dy = [-1,1,0,0]
  17.        
  18.         q = collections.deque()
  19.         q.append((x,y))
  20.         visited[x][y] = 1
  21.         while q:
  22.             xx, yy = q.popleft()
  23.             for i in range(4):
  24.                 rx, ry = xx + dx[i], yy + dy[i]
  25.                 if rx <0 or ry < 0 or rx > len(grid)-1 or ry > len(grid[0])-1:
  26.                     continue
  27.                 if visited[rx][ry] == 0 and grid[rx][ry] == '1':
  28.                     q.append((rx, ry))
  29.                     visited[rx][ry] = 1
  30.        
  31.         self.res += 1
  32.         return
  33.                    
  34.     def numIslands(self, grid):
  35.         """
  36.        :type grid: List[List[str]]
  37.        :rtype: int
  38.        """
  39.         self.res = 0
  40.        
  41.         if not grid or not grid[0]:
  42.             return self.res
  43.        
  44.         visited = [0] * len(grid)
  45.         for i in range(len(grid)):
  46.             visited[i] = [0] * len(grid[0])
  47.            
  48.         for i in range(len(grid)):
  49.             for j in range(len(grid[0])):
  50.                 if grid[i][j] == '1' and visited[i][j] == 0:
  51.                     self.neighbors(grid, visited, i, j)
  52.        
  53.         return self.res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement