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

Upload New File

parent 1765c23e
#!/usr/bin/env/python3
"""
Name = Siu Pui Chung Jacky
Student number = 1047527
Script for Connected Components
input: A simple directed graph with n≤103 vertices in the edge list format.
output: The number of connected components in the graph.
"""
from sys import argv
def producegraph(edgelist):
"""
Description: store edgelist as dictionary
Input: edgelist, bi directional simple graph in edge list format
Output: numvertices, int of number of vertices in the graph
graphdict, dictioanry of uni-directed graph
"""
graph = {}
#initialise default list
numvertices, edge = map(int, f.readline().strip().split(" "))
graph = {i+1:[] for i in range(numvertices)}
for line in edgelist:
line = line.strip()
key, value = int(line.split()[0]), int(line.split()[1])
#bi directional hence it can be value and key at the same time
graph[key].append(value)
graph[value].append(key)
return numvertices, graph
def dfs(vertex, connected_component, graphdict):
"""
Description: recursive algorithm that connect connectable components
Input: vertex, current vertex being inspected
connected_component, empty list of connected componenets associated
with current vertex
graphdict, dictionaryof uni-directed graph
Output: connected_component, list of connected componenets associated
with current vertex
"""
visited[vertex] = True
connected_component.append(vertex)
#recursive part which applies dfs function to neighbours of current vertex
for neighbour in graphdict[vertex]:
if visited[neighbour] == False:
connected_component = dfs(neighbour, connected_component, graphdict)
return connected_component
if __name__ == "__main__":
with open(argv[1]) as f:
numvertices, graphdict = producegraph(f)
f.close()
print(graphdict)
#set all vertex in visited as False
visited = [False for i in range(numvertices+1)]
connected_component_list = []
for vertex in range(1, (numvertices + 1)):
#break up non-connected components by initilizing connected_component
if visited[vertex] == False:
connected_component = []
connected_component_list.append(dfs(vertex, connected_component, graphdict))
print(connected_component_list)
print(len(connected_component_list))
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