Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.3 KiB

  1. # Python3 program to print DFS traversal
  2. from collections import defaultdict
  3. # This class represents a directed graph using
  4. # adjacency list representation
  5. class Graph:
  6. # Constructor
  7. def __init__(self):
  8. # default dictionary to store graph
  9. self.graph = defaultdict(list)
  10. # function to add an edge to graph
  11. def addEdge(self, u, v):
  12. self.graph[u].append(v)
  13. # A function used by DFS
  14. def DFSUtil(self, v, visited):
  15. # Mark the current node as visited
  16. # and print it
  17. visited[v] = True
  18. print(v, end = ' ')
  19. # Recur for all the vertices
  20. # adjacent to this vertex
  21. for i in self.graph[v]:
  22. if visited[i] == False:
  23. self.DFSUtil(i, visited)
  24. # The function to do DFS traversal. It uses
  25. # recursive DFSUtil()
  26. def DFS(self, v):
  27. # Mark all the vertices as not visited
  28. visited = [False] * (len(self.graph))
  29. # Call the recursive helper function
  30. # to print DFS traversal
  31. self.DFSUtil(v, visited)
  32. # Driver code
  33. # Create a graph given
  34. # in the above diagram
  35. g = Graph()
  36. g.addEdge(0, 1)
  37. g.addEdge(0, 2)
  38. g.addEdge(1, 2)
  39. g.addEdge(2, 0)
  40. g.addEdge(2, 3)
  41. g.addEdge(3, 3)
  42. print("Following is DFS from (starting from vertex 2)")
  43. g.DFS(2)