Skip to content

Commit

Permalink
Graph, Deep First Search, Graph with Matrix, Graph with List
Browse files Browse the repository at this point in the history
  • Loading branch information
frmatias committed Jun 22, 2017
1 parent 1ce58ef commit 285720f
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Graphs/Deep_First_Search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Graph:

def __init__(self, vertex):
self.vertex = vertex
self.graph = [[0] * vertex for i in range(vertex) ]
self.visited = [False] * vertex

def add_edge(self, u, v):
self.graph[u - 1][v - 1] = 1
self.graph[v - 1][u - 1] = 1

def show(self):

for i in self.graph:
for j in i:
print(j, end=' ')
print(' ')


def dfs(self, u):
self.visited[u - 1] = True
print('%d visited' % u)
for i in range(1, self.vertex + 1):
if self.graph[u - 1][i - 1] == 1 and self.visited[i - 1] == False:
self.dfs(i)


g = Graph(5)

g.add_edge(1,4)
g.add_edge(4,2)
g.add_edge(4,5)
g.add_edge(2,5)
g.add_edge(5,3)
print(g.dfs(1))
27 changes: 27 additions & 0 deletions Graphs/Graph_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Graph:
def __init__(self, vertex):
self.vertex = vertex
self.graph = [[0] for i in range(vertex)]

def add_edge(self, u, v):
self.graph[u - 1].append(v - 1)

def show(self):
for i in range(self.vertex):
print('%d: '% (i + 1), end=' ')
for j in self.graph[i]:
print('%d-> '% (j + 1), end=' ')
print(' ')



g = Graph(5)

g.add_edge(1,3)
g.add_edge(2,3)
g.add_edge(3,4)
g.add_edge(3,5)
g.add_edge(4,5)

g.show()

30 changes: 30 additions & 0 deletions Graphs/Graph_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Graph:

def __init__(self, vertex):
self.vertex = vertex
self.graph = [[0] * vertex for i in range(vertex) ]

def add_edge(self, u, v):
self.graph[u - 1][v - 1] = 1
self.graph[v - 1][u - 1] = 1

def show(self):

for i in self.graph:
for j in i:
print(j, end=' ')
print(' ')




g = Graph(5)

g.add_edge(1,3)
g.add_edge(2,3)
g.add_edge(3,4)
g.add_edge(3,5)
g.add_edge(4,5)

g.show()

0 comments on commit 285720f

Please sign in to comment.