-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_undericted_path.py
53 lines (44 loc) · 1016 Bytes
/
graph_undericted_path.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
# edges list
edges = [
['i', 'j'],
['k', 'i'],
['m', 'k'],
['k', 'l'],
['o', 'n'],
]
# adjacency list
# graph = {
# 'i': ['j', 'k'],
# 'j': ['i'],
# 'k': ['i', 'm', 'l', 'j'],
# 'm': ['k'],
# 'l': ['k'],
# 'o': ['n'],
# 'n': ['o'],
# }
def undirected_path(edges, node_a, node_b):
graph = build_graph(edges)
s = set()
return has_path(graph, node_a, node_b, s)
def has_path(graph, src, dst, visited):
if src == dst:
return True
if src in visited:
return False
visited.add(src)
for each in graph[src]:
if has_path(graph, each, dst, visited):
return True
return False
def build_graph(edges):
graph = {}
for edge in edges:
a, b = edge
if a not in graph:
graph[a] = []
if b not in graph:
graph[b] = []
graph[a].append(b)
graph[b].append(a)
return graph
print("undirected path: ", undirected_path(edges, 'j', 'o'))