Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. def DFSUtil(graph, v, visited):
  2.  
  3.     visited[v] = True               # Mark the current node as visited and print it
  4.     print(v, end = ' ')
  5.  
  6.     for i in graph[v]:              # Recur for all the vertices adjacent to this vertex
  7.         if visited[i] == False:
  8.             DFSUtil(graph, i, visited)
  9.  
  10.  
  11. def DFS(graph, v):
  12.    
  13.     visited = [False] * (len(graph))     # Mark all the vertices as not visited
  14.     DFSUtil(graph, v, visited)
  15.  
  16.  
  17.  
  18.  
  19.  
  20. def BFS(graph, s):
  21.  
  22.     visited = [False] * (len(graph))         # Mark all the vertices as not visited
  23.  
  24.     queue = []                   # Create a queue for BFS
  25.  
  26.     queue.append(s)              # Mark the source node as visited and enqueue it
  27.     visited[s] = True
  28.  
  29.     while queue:
  30.  
  31.         s = queue.pop(0)             # Dequeue a vertex from queue and print it
  32.         print (s, end = " ")
  33.  
  34.     for i in graph[s]:          # Get all adjacent vertices of the dequeued vertex s.
  35.         if visited[i] == False:         # If a adjacent has not been visited,
  36.                 queue.append(i)         # then mark it visited and enqueue it
  37.                 visited[i] = True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement