题目:
![题目](https://i-blog.csdnimg.cn/blog_migrate/4fbab2fb08387610f0afbfd330c0801b.png)
解析:
代码:
import queue
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
x_length = len(grid)
y_length = len(grid[0]) if x_length > 0 else 0
islands = 0
arr = [[False] * y_length for i in range(x_length)]
q = queue.Queue(y_length * x_length)
direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in range(x_length):
for j in range(y_length):
if arr[i][j] == False and grid[i][j] == '1':
q.put((i, j))
arr[i][j] = True
islands += 1
while not q.empty():
temp = q.get()
for x,y in direction:
n_x = temp[0] + x
n_y = temp[1] + y
if 0 <= n_x < x_length and 0 <= n_y < y_length and grid[n_x][n_y] == '1' and arr[n_x][n_y] == False:
q.put((n_x, n_y))
arr[n_x][n_y] = True
return islands
import queue
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
self.x_length = len(grid)
self.y_length = len(grid[0]) if self.x_length > 0 else 0
islands = 0
visited = [[False] * self.y_length for i in range(self.x_length)]
q = queue.LifoQueue()
self.direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in range(self.x_length):
for j in range(self.y_length):
if not visited[i][j] and grid[i][j] == '1':
islands += 1
self.DFS(grid, i, j, visited)
return islands
def DFS(self, grid, i, j, visited):
visited[i][j] = True
for x,y in self.direction:
if 0 <= i+x < self.x_length and 0 <= j+y < self.y_length and not visited[i+x][j+y] and grid[i][j] == '1':
self.DFS(grid, i+x, y+j, visited)
总结:
- 广度优先法很适合这道题,但是效率低,只打败了百分之三十多的人。
- 这里的深度优先法,采用递归的方式,形式简洁易懂。