zoukankan      html  css  js  c++  java
  • leetcode1030

     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,因此按层遍历的顺序,即为所求。

  • 相关阅读:
    Git :版本控制工具进阶
    Git 提交本地代码
    Git创建代码仓库
    Git
    SQLlite数据库的增删改查
    Android学习第十天
    Android学习第九天
    Android学习第八天
    Android学习第七天
    【k8s】Deployment
  • 原文地址:https://www.cnblogs.com/asenyang/p/10744717.html
Copyright © 2011-2022 走看看