Last active
August 11, 2019 22:05
-
-
Save Biostate/8ece06e5e4770978402154da04a016d5 to your computer and use it in GitHub Desktop.
Problem Solved with Adjacency List Representation
This file contains 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
# A Simple Queue | |
class Queue: | |
def __init__(self): | |
self.nodes = [] | |
def enqueue(self,x): | |
self.nodes = self.nodes + x | |
def dequeue(self): | |
if self.have(): | |
return self.nodes.pop(0) | |
def have(self): # Checks if Queue is empty | |
return len(self.nodes) | |
def BFS(x): | |
if x not in visiteds: | |
visiteds.append(x) | |
Q.enqueue(nod[x]) | |
for i in nod[x]: | |
if i not in visiteds: | |
if path[i] == None: | |
path[i] = x | |
if Q.have(): | |
BFS(Q.dequeue()) | |
# Adjacency List represented as an array on the bottom | |
# 0 -> 2,4 | |
# 1 -> 2,3,5 | |
# 2 -> 0,1,5 | |
# 3 -> 1,5,7 | |
# 4 -> 0,6 | |
# 5 -> 1,2,3 | |
# 6 -> 4,5 | |
# 7 -> 3 | |
nod = [ | |
[2,4], | |
[2,3,5], | |
[0,1,5], | |
[1,5,7], | |
[0,6], | |
[1,2,3,6], | |
[4,5], | |
[3] | |
] | |
visiteds = [] # Stores visiteds | |
path = [None] * len(nod) # Stores path | |
Q = Queue() | |
startNode = 2 # 2 is the where BFS start position | |
BFS(startNode) | |
print("Index\tParent") | |
for i in range(len(path)): | |
print(f"{i}\t{path[i]} <- Start Node" if startNode == i else f"{i}\t{path[i]}") | |
# If you want to run some examples in the code you can use the link on the bottom. | |
# The website generates random BFS graphs. Just modify Adjacency table in "nod" array. | |
# https://www.cs.usfca.edu/~galles/visualization/BFS.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment