Skip to content

Instantly share code, notes, and snippets.

@loisgh
Created March 2, 2018 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loisgh/412b886bb6cd5b459fae697b38264303 to your computer and use it in GitHub Desktop.
Save loisgh/412b886bb6cd5b459fae697b38264303 to your computer and use it in GitHub Desktop.
class Node:
# Constructor to initialize the node object
def __init__(self, data, neighbors=[]):
self.data = data
self.neighbors = []
class Graph:
def __init__(self):
self.head = None
def create_graph(self, adj_dict):
graph = Graph()
keys = sorted(adj_dict.keys())
nodes = self.create_nodes(keys)
for key in keys:
the_neighbors = adj_dict[key]
#move to method in Node
for neighbor in the_neighbors:
nodes[key].neighbors.append(nodes[neighbor])
self.head = nodes['A']
return graph
def create_nodes(self, keys):
node_dict = {}
for key in keys:
new_node = Node(key)
node_dict[key] = new_node
return node_dict
def print_graph(self, current, visited={}):
while current and current.data not in visited:
print(current.data)
visited[current.data] = 0
print self.print_neighbors(current)
for neighbor in current.neighbors:
current = neighbor
return self.print_graph(current, visited)
def print_neighbors(self, current):
n_string = " "
for neighbor in current.neighbors:
n_string += neighbor.data
n_string += " "
return n_string
def create_adj_dict(vert_list):
adj_dict = {}
for vertex in vert_list:
if vertex[0] in adj_dict:
adj_dict[vertex[0]].append(vertex[1])
else:
adj_dict[vertex[0]] = [vertex[1]]
return adj_dict
def main():
list_of_vertices = [['A','B'], ['A','E'], ['A','H'],
['B','C'], ['B','H'], ['B','D'],
['C','D'], ['C','G'], ['C','B'],
['D','E'], ['D','C'], ['D','B'],
['E','F'], ['E','D'], ['E','A'],
['F','G'], ['F','E'], ['F','B'],
['G','H'], ['G','F'], ['G','C'],
['H','A'], ['H','G'], ['H','D']]
adj_dict = create_adj_dict(list_of_vertices)
print adj_dict
print sorted(adj_dict.keys())
graph = Graph()
graph.create_graph(adj_dict)
visited = {}
print graph.print_graph(graph.head, visited)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment