创建一个数字矩阵和起点,用于遍历/搜索程序



我正在尝试创建一个python类,该类建立一个由n x n个数字组成的网格,然后基于网格中的起点,使用该网格进行深度优先和广度优先的搜索/遍历。当调用类作为测试的一部分时,将定义的变量是starting row+the starting column(定义起点(和size of the row+size of the column(定义二维网格空间(。课程开始时是这样的:

class Graph:
def __init__(self, start_row: int, start_col: int, size_row: int, size_col: int):
#constructor
self.graph = [[0] * size_col for _ in range(size_row)]
self.bfs(start_row, start_col)

我能够根据调用对象时包含的输入创建矩阵,它看起来像这样:

def test_graph():
g = Graph(3, 5, 8, 9)

广度优先搜索算法的其余代码如下所示,与另一种方法构建的类相同:

BFS功能

def bfs(self,s):  # this is our function using params as 
# visited nodes, the graph, and the node
# initialize  all vertices as not visited
visited = [False] * (max(self.graph)+1)
# create a BFS queue
queue = []
# mark the source node as visited and enqueue it
queue.append(s)
visited[s] = True
# while loop to keep the routine running until nothing 
#left to visit
while queue:
# remove a vertex from queue
s = queue.pop()
# get all adjacent vertices of the last considered 
#vertex; if adjacency not visited, mark
# ~ it visited and enqueue
for i in self.graph[s]:
if visited[i] == False:
queue.append[i]
visited[i] = True

我遇到的问题是,我的对象返回的是全零数组,而不是BFS的结果。我的类中是否缺少导致对象无法在给定的类输入上执行BFS方法的内容?

此中存在多个问题

  1. 用两个参数(行和列(调用self.bfs(),而定义只有一个参数(s(
  2. max(self.graph)将返回一个列表,您不能用它初始化visited
  3. s=queue.pop()实际上会使函数表现为dfs而不是bfs。.pop()从列表末尾弹出。如果您有[1,2,3]并调用pop(),则3将被返回并表现为堆栈。为了使它表现得像一个队列,应该使用queue.pop(0)
  4. 不确定使用一维访问数组的逻辑是什么,以及s指的是什么

最新更新