广度优先遍历中的Python“列表索引超出范围”错误

时间:2017-07-24 15:30:01

标签: python algorithm breadth-first-search

我正在尝试在python中创建一个BFS。虽然我是正确的邻接列表但Python显示"list index out of range"错误,但BFS答案始终不正确。

下面是python代码,我添加了边(1, 2), (2, 3)(3, 3)

我试图从顶点2找到BFS,

from collections import defaultdict

# This class represents a directed graph using adjacency
# list representation
class Graph:

    # Constructor
    def __init__(self):

        # default dictionary to store graph
        self.graph = defaultdict(list)

    # function to add an edge to graph
    def addEdge(self,u,v):
        self.graph[u].append(v)

    # Function to print a BFS of graph
    def BFS(self, s):

        # Mark all the vertices as not visited
        visited = [False]*(len(self.graph))

        # Create a queue for BFS
        queue = []

        # Mark the source node as visited and enqueue it
        queue.append(s)
        visited[s] = True

        while queue:

            # Dequeue a vertex from queue and print it
            s = queue.pop(0)
            print s,

            # Get all adjacent vertices of the dequeued
            # vertex s. If a adjacent has not been visited,
            # then mark it visited and enqueue it
            for i in self.graph[s]:

                if visited[i] == False:

                    queue.append(i)
                    visited[i] = True




# Create a graph 
g = Graph()

g.addEdge(1, 2)
g.addEdge(2, 3)
g.addEdge(3, 3)

print "Following is Breadth First Traversal (starting from vertex 2)"
g.BFS(2)

它显示的错误;

Following is Breadth First Traversal (starting from vertex 2)
2
Traceback (most recent call last):
  File "test.py", line 58, in <module>
    g.BFS(2)
  File "test.py", line 42, in BFS
    if visited[i] == False:
IndexError: list index out of range

不确定,为什么显示超出范围。我已将vertex[1]vertex[2]vertex[3]初始化为False。此外,graph[1]graph[2]graph[3]正在维护适当的邻接列表。

此外,BFS答案应为2 3,但仅提供2

2 个答案:

答案 0 :(得分:1)

visited数组的长度为3,因此visited[3]超出范围。

问题主要是因为python列表从0开始索引,因此行visited = [False]*(len(self.graph))不会创建条目visited[len(self.graph)]

此外,为了调试,我建议您在无法查看正在发生的操作的指令之前打印ivisited列表。

答案 1 :(得分:0)

替换visited = [False]*(len(self.graph))
有了这个visited = [False]*(len(self.graph)+1)