Created
December 10, 2020 15:43
-
-
Save BastinRobin/396077797a23fdc6f5d1e43f5cedb614 to your computer and use it in GitHub Desktop.
BFS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Using a Python dictionary to act as an adjacency list | |
graph = { | |
'A' : ['B','C'], | |
'B' : ['D', 'E'], | |
'C' : ['F'], | |
'D' : [], | |
'E' : ['F'], | |
'F' : [] | |
} | |
def dfs(_visited, graph, node): | |
if node not in _visited: | |
_visited.add(node) | |
print(node) | |
for neighbour in graph[node]: | |
dfs(_visited, graph, neighbour) | |
# Driver Code | |
# source = input("Enter the source") | |
# dfs(_visited, graph, source) | |
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 | |
# source = input("Enter the source") | |
# bfs(visited, graph, source) | |
while True: | |
print("\n1-BREADTH FIRST SEARCH") | |
print("2-DEPTH FIRST SEARCH") | |
print("0-EXIT") | |
ch = int(input("ENTER YOUR CHOICE-: \n")) | |
if ch == 0: | |
print("EXIT") | |
break; | |
if ch==1: | |
source = input("ENTER THE 1 SOURCE: ") | |
bfs([], graph, source ) | |
if ch==2: | |
source = input("ENTER THE 2 SOURCE: ") | |
dfs(set(), graph, source) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment