-
Notifications
You must be signed in to change notification settings - Fork 0
/
022hasPath.py
63 lines (53 loc) · 1.5 KB
/
022hasPath.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
from tabnanny import verbose
def depthHasPath(graph,source,target):
stack = [source]
while len(stack)>0:
current = stack[-1]
if current == target:
return True
stack = stack[:-1:]
for ele in graph[current]:
stack.append(ele)
return False
def depthRecursivHasPath(graph,source,target):
if source == target:
return True
elif len(graph[source]) > 0:
for ele in graph[source][::-1]:
if depthRecursivHasPath(graph,ele,target):
return True
return False
def breadthHasPath(graph,source,target):
stack = [source]
while len(stack)>0:
current = stack[0]
stack = stack[1::]
if current == target:
return True
for ele in graph[current]:
stack.append(ele)
return False
def testHasPaths(verbose = False):
result = 1
for source in graph.keys():
print(f'{source}| ',end=' ') if verbose else None
for target in graph.keys():
result1 = depthHasPath(graph,source,target)
result2 = depthRecursivHasPath(graph,source,target)
result3 = breadthHasPath(graph,source,target)
thisResult = result1==result2 and result1==result3
result = result*thisResult
print(target,result1==result2 and result1==result3,end=' ') if verbose else None
print() if verbose else None
print(f'Has path test: {bool(result)}') if verbose else None
return bool(result)
graph = {
'f':['g','i'],
'g':['h'],
'h':[],
'i':['g','k'],
'j':['i'],
'k':[],
}
if __name__ == '__main__':
testHasPaths(verbose=True)