-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGraph.py
71 lines (70 loc) · 2.21 KB
/
Graph.py
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
from collections import deque
class Graph:
def __init__(self):
self.__nodeLookUp={}
class Node:
def __init__(self,id,adjacent):
self.__id = id
self.__adjacent = adjacent
@property
def id(self):
return self.__id
@property
def adjacent(self):
return self.__adjacent
def addNodes(self,nodes):
for key in nodes:
node = self.Node(key,[])
self.__nodeLookUp[key] = node
def __getNode(self,id):
return self.__nodeLookUp[id]
def addEdge(self,source,destination):
s = self.__getNode(source)
d = self.__getNode(destination)
s.adjacent.append(d)
def hasPathBFS(self,source, destination):
s = self.__getNode(source)
d = self.__getNode(destination)
return self.__hasPathBFSVisit(s,d)
def hasPathDFS(self,source, destination):
s = self.__getNode(source)
d = self.__getNode(destination)
visited = set()
return self.__hasPathDFSVisit(s,d,visited)
def __hasPathBFSVisit(self,source, destination):
visited = set()
l = deque()
l.append(source)
while(l):
node = l.popleft()
if(node == destination):
return True
else:
if(node.id in visited):
continue
visited.add(node.id)
for child in node.adjacent:
l.append(child)
return False
def __hasPathDFSVisit(self,source, destination, visited):
if(source.id in visited):
return False
else:
visited.add(source.id)
if(source == destination):
return True
for child in source.adjacent:
if(self.__hasPathDFSVisit(child,destination, visited)):
return True
return False
if __name__ == '__main__':
g = Graph()
vertices = [0,1,2,3,4,5,6]
g.addNodes(vertices)
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,3)
g.addEdge(2,4)
g.addEdge(3,5)
print(g.hasPathDFS(1,5))
print(g.hasPathBFS(0,1))