Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 200. Number of Islands
- 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.
- Input:
- 11110
- 11010
- 11000
- 00000
- Output: 1
- 类似这种需要求出在matrix中连续字符的题,以后就都用我最会用的 BFS 的方法。先要做出一个 Visteid[][] matrix, 然后遍历每一个在matrix里面的值。如果,matrix[i][j] == "1" and visited[i][j] == 0 时,开始带入到 BFS 中。 在BFS中遍历 上下左右四个方向的值,如果符合条件就加到BFS的queue中,当queue is None, 说明找到了一个结果。然后返回继续遍历没有被visited过得值
- class Solution(object):
- def neighbors(self, grid, visited, x, y):
- dx = [0,0,-1,1]
- dy = [-1,1,0,0]
- q = collections.deque()
- q.append((x,y))
- visited[x][y] = 1
- while q:
- xx, yy = q.popleft()
- for i in range(4):
- rx, ry = xx + dx[i], yy + dy[i]
- if rx <0 or ry < 0 or rx > len(grid)-1 or ry > len(grid[0])-1:
- continue
- if visited[rx][ry] == 0 and grid[rx][ry] == '1':
- q.append((rx, ry))
- visited[rx][ry] = 1
- self.res += 1
- return
- def numIslands(self, grid):
- """
- :type grid: List[List[str]]
- :rtype: int
- """
- self.res = 0
- if not grid or not grid[0]:
- return self.res
- visited = [0] * len(grid)
- for i in range(len(grid)):
- visited[i] = [0] * len(grid[0])
- for i in range(len(grid)):
- for j in range(len(grid[0])):
- if grid[i][j] == '1' and visited[i][j] == 0:
- self.neighbors(grid, visited, i, j)
- return self.res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement