Commit b4f85bac authored by Siu, Pui Chung's avatar Siu, Pui Chung
Browse files

Upload New File

parent 87d63cfa
#!/usr/bin/env/python3
"""
Name = Siu Pui Chung Jacky
Student number = 1047527
Script for Breadth-First Search
input: A simple directed graph with n≤103 vertices in the edge list format.
output: An array D[1..n] where D[i] is the length of a shortest path
from the vertex 1 to the vertex i (D[1]=0). If i is not reachable
from 1 set D[i] to −1.
"""
from sys import argv
def producegraph(edgelist):
graphdict = {}
#initialise default list
numvertices, edge = map(int, f.readline().strip().split(" "))
for i in range(1, numvertices + 1):
graphdict[i] = []
for line in edgelist:
line = line.strip()
key, value = int(line.split()[0]), int(line.split()[1])
if key in graphdict.keys():
graphdict[key].append(value)
return numvertices, graphdict
def bfsgraph(vertice_num, graphdict):
#stack = where to go next, path = list that store visited vertice
stack, path = [], []
distance = {}
#initialise distance dictionary
for i in range(vertice_num):
distance[i + 1] = 0
#initialised visited nodes with starting vertice 1
stack.append(1)
#while stack is not empty
while stack:
#establish vertex as current vertex from list stack
vertex = stack.pop(0)
#add current vertex to visited vertice list path
path.append(vertex)
#for each neighbour of current vertex
for neighbour in graphdict[vertex]:
#if neigbour vertex not within path
if neighbour not in path:
#add 1 for each time it passes through a vertex
distance[neighbour] = distance[vertex] + 1
path.append(neighbour)
#add neigbour vertex to list stack
stack.append(neighbour)
#for unreachable vertex from starting vertice = -1
for k in distance.keys():
if k not in path:
distance[k] = -1
return path, distance
if __name__ == "__main__":
with open(argv[1]) as f:
numvertices, graphdict = producegraph(f)
f.close()
path, distance = bfsgraph(numvertices, graphdict)
distancelist = []
for i in range(int(numvertices)):
distancelist.append(distance[i+1])
with open("answer.txt", "w") as h:
for i in range(int(numvertices)):
h.write(str(distance[i+1]).rstrip('\n') + " ")
h.close()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment