Untitled

unknown
plain_text
7 months ago
1.9 kB
4
Indexable
Never
```graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = [] # List to keep track of visited nodes.
queue = []     #Initialize a queue

def bfs(visited, graph, node):
visited.append(node)
queue.append(node)

while queue:
s = queue.pop(0)
print (s, end = " ")

for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
bfs(visited, graph, 'A')

dfs

# Python3 program to print DFS traversal
# from a given graph
from collections import defaultdict

# This class represents a directed graph using
class Graph:

# Constructor
def __init__(self):

# Default dictionary to store graph
self.graph = defaultdict(list)

# Function to add an edge to graph
self.graph[u].append(v)

# A function used by DFS
def DFSUtil(self, v, visited):

# Mark the current node as visited
# and print it
print(v, end=' ')

# Recur for all the vertices
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)

# The function to do DFS traversal. It uses
# recursive DFSUtil()
def DFS(self, v):

# Create a set to store visited vertices
visited = set()

# Call the recursive helper function
# to print DFS traversal
self.DFSUtil(v, visited)

# Driver's code
if __name__ == "__main__":
g = Graph()