Skip to content

Bug in graphs/breadth_first_search.py #6334

@itsamirhn

Description

@itsamirhn

As you can see in the code below:

def add_edge(self, from_vertex: int, to_vertex: int) -> None:
"""
adding the edge between two vertices
>>> g = Graph()
>>> g.print_graph()
>>> g.add_edge(0, 1)
>>> g.print_graph()
0 : 1
"""
if from_vertex in self.vertices:
self.vertices[from_vertex].append(to_vertex)
else:
self.vertices[from_vertex] = [to_vertex]

this code only works for directed graphs and the BFS algorithm is wrong.
For example in this minimal example:

g = Graph()
g.add_edge(0, 1)
print(g.bfs(1))

You will get a KeyError: 1 because the node number 1 has not been added to the self.verices.

If you look closer, this code will raise a error too even when the graph is not directed:

g = Graph()
g.add_edge(0, 1)
print(g.bfs(0))

Cause in the BFS algorithm, when it reaches to node number 1, the previous problem appears here too.

This code is a little bugy and It should have stronger tests. Also the graphs/breadth_first_search_2.py file can be merged with this one too.

Please assign fixing this issue to me if I'm right about this problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions