-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgraph.py
More file actions
96 lines (73 loc) · 2.75 KB
/
Copy pathgraph.py
File metadata and controls
96 lines (73 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import algorithm_and_datastructure.graphs.graph_helper as gh
class Graph:
def __init__(self,vertexes):
self.arr = []
for i in range(vertexes):
self.arr.append(gh.LinkedList())
def add_vertex(self):
self.arr.append(gh.LinkedList())
def add_edge(self,s,d):
if s < len(self.arr) and d < len(self.arr):
ll = self.arr[s]
ll.add(d)
def display(self):
print("Graph display")
for i,e in enumerate(self.arr):
print("vertex ", i , " has conneted edge :=> ", end="")
c = e.head
while c:
print(c.data, " - ", end="")
c = c.next
print()
def bfs_traversal_helper(self, g, source, visited):
result = ""
queue = gh.Q()
queue.enqueue(source)
visited[source] = True # Mark as visited
# Traverse while queue is not empty
while len(queue) > 0 :
# Dequeue a vertex/node from queue and add it to result
current_node = queue.dequeue()
result += str(current_node)
nn = g.arr[current_node].head
while nn is not None:
if not visited[nn.data]:
queue.enqueue(nn.data)
# result += nn.data
visited[nn.data] = True
nn = nn.next
return result, visited
def bfs(self,g,source):
visited = [False] * len(g.arr)
result, visited = self.bfs_traversal_helper(g,source,visited)
for i,e in enumerate(visited):
if not e:
result_new, visited = self.bfs_traversal_helper(g,i,visited)
result += result_new
return result
def dfs_traversal_helper(self, g, source, visited):
result = ""
stack = gh.Stack()
stack.push(source)
visited[source] = True # Mark as visited
# Traverse while queue is not empty
while len(stack) > 0 :
# Dequeue a vertex/node from queue and add it to result
current_node = stack.pop()
result += str(current_node)
nn = g.arr[current_node].head
while nn is not None:
if visited[nn.data] is False:
stack.push(nn.data)
# result += nn.data
visited[nn.data] = True
nn = nn.next
return result, visited
def dfs_traversal(self,g,source):
visited = [False] * len(g.arr)
result, visited = self.bfs_traversal_helper(g,source,visited)
for i,e in enumerate(visited):
if not e:
result_new, visited = self.bfs_traversal_helper(g,i,visited)
result += result_new
return result