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!