1 class Solution(object):
 2     def __init__(self):
 3         self.List = list()
 4 
 5     def bfs(self,R,C,S,V):
 6         T = list()
 7         while len(S) >0:
 8             node = S.pop(0)
 9             if node[0]-1>=0 and V[node[0]-1][node[1]] == 0:
10                 V[node[0]-1][node[1]] = 1
11                 T.append([node[0]-1,node[1]])
12                 self.List.append([node[0]-1,node[1]])
13             if node[0]+1<R and V[node[0]+1][node[1]] == 0:
14                 V[node[0]+1][node[1]] = 1
15                 T.append([node[0]+1,node[1]])
16                 self.List.append([node[0]+1,node[1]])
17             if node[1]-1>=0 and V[node[0]][node[1]-1] == 0:
18                 V[node[0]][node[1]-1] = 1
19                 T.append([node[0],node[1]-1])
20                 self.List.append([node[0],node[1]-1])
21             if node[1]+1<C and V[node[0]][node[1]+1] == 0:
22                 V[node[0]][node[1]+1] = 1
23                 T.append([node[0],node[1]+1])
24                 self.List.append([node[0],node[1]+1])
25         if len(T)>0:
26             self.bfs(R,C,T,V)
27 
28 
29 
30     def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> 'List[List[int]]':
31         stack = list()
32         visited = [[0 for col in range(C)] for row in range(R)]
33         stack.append([r0,c0])
34         visited[r0][c0] = 1
35         self.List.append([r0,c0])
36         self.bfs(R,C,stack,visited)
37         return self.List

典型的BFS算法,每一“层”都比前一层的距离多1,因此按层遍历的顺序,即为所求。

posted on 2019-04-21 12:40  Sempron2800+  阅读(221)  评论(0编辑  收藏  举报