Skip to content

Instantly share code, notes, and snippets.

@prakashn27
Created January 12, 2017 00:40
Show Gist options
  • Save prakashn27/84e8cca107c6e0ad7fddd2c133432593 to your computer and use it in GitHub Desktop.
Save prakashn27/84e8cca107c6e0ad7fddd2c133432593 to your computer and use it in GitHub Desktop.
# Graph implementation in python
# adjacency list representation
class Graph:
def __init__(self, no_of_nodes):
self.n = no_of_nodes
self.al = []
for i in range(no_of_nodes):
self.al.append(list())
def add_edge(self, x, y):
if x < len(self.al) and y < len(self.al):
self.al[x].append(y)
self.al[y].append(x)
def print_graph(self):
i = 0
for node in self.al:
print(i, '->', node)
i = i + 1
def run():
g = Graph(5)
g.add_edge(0,1)
g.add_edge(0, 2)
g.add_edge(0, 3)
g.print_graph()
if __name__ == "__main__":
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment