0

I'm here trying to share my depth first-search (DFS) implementation. I'm trying to learn how can it traverse in a graph that is undirected, meaning that not all nodes are making into one graph, but two different ones. I was looking for the small basics of DFS with one graph only. And I came across to a problem in "what would happen if there are more than one graph and are not connected?" So I started to look around how to do it by using my knowledge from the simple DFS implementation. However, it is a little bit more complicated than I thought. Here is the code sample that I came across:

"""DFS implemention."""

    adjacency_matrix = {
                        1: [2, 3],
                        2: [4, 5],
                        3: [5],
                        4: [6],
                        5: [6],
                        6: [7],
                        7: [],
                        8: [9],
                        9: [8]
                        }

        def DFS_un(graph):
        """Traversal for undirected graphs."""
            vertices = graph[0]
            edges = graph[1]

        def visit(vertex):
            if vertex in visited:
                return
            visited.add(vertex)
            print(vertex)
            if vertex in edges:
                for e in edges[vertex]:
                    visit(e)
        visited = {}
        for v in vertices:
            visit(v)

    if __name__ == '__main__':
        DFS_un(adjacency_matrix)

And the error message says this:

Traceback (most recent call last):
  File "dfs.py", line 33, in <module>
    DFS_dis(adjacency_matrix)
  File "dfs.py", line 17, in DFS_dis
    vertices = graph[0]
KeyError: 0

If you see, I'm using one graph, but it has undirected numbers, which is 8 and 9 (8<->9). Why am I not getting my output correctly? Sorry, learning some Python3 too :). Thanks for your help!

Zeid Tisnes
  • 396
  • 5
  • 22

2 Answers2

1

You want:

vertices = graph.keys()
edges = graph.values()

'Graph' is a dictionary object. The graph[0] notation says find me the value associated with the key=0. Since you have no key=0 you get an error.

You might be confusing dictionaries with lists. my_list[0] says get me the value at position 0 in my_list.

blueenvelope
  • 699
  • 7
  • 15
0

I found my problem already. @blueenvelope was right with the idea of the dictionary because there are no KeyWords used and thus giving me 0 for some reason... At the end, it finally reads the whole graph list from unconnected vertices.

My variables vertices and edges were incorrectly implemented and quickly understood it's purpose. Keys is used to find particular dictionaries, so I was pulling keys from the graph vertex. Same goes for my edges, but also pulling the values of those edges from a specific key. Here is the full fixed code:

adjacency_matrix = {
                    1: [2, 3],
                    2: [4, 5],
                    3: [5],
                    4: [6],
                    5: [6],
                    6: [7],
                    7: [],
                    8: [9],
                    9: [8]
                    }

def DFS_un(graph):
    """Traversal for undirected graphs."""
    vertices = graph.keys()
    edges = graph.values()
    visited = []

    def visit(vertex):
        if vertex in visited:
            return
        print("Visited vertex: ")
        visited.append(vertex)
        print(visited)
        print("Current vertex: ")
        print(vertex)
        print("\n")
        if vertex in edges:
            for e in edges[vertex]:
                visit(e)
    for v in vertices:
        visit(v)

if __name__ == '__main__':
    DFS_un(adjacency_matrix)
Zeid Tisnes
  • 396
  • 5
  • 22