How do you trace the path of a Breadth-First Search, such that in the following example:
If searching for key 11
, return the shortest list connecting 1 to 11.
JavaScript
x
2
1
[1, 4, 7, 11]
2
Advertisement
Answer
You should have look at http://en.wikipedia.org/wiki/Breadth-first_search first.
Below is a quick implementation, in which I used a list of list to represent the queue of paths.
JavaScript
1
31
31
1
# graph is in adjacent list representation
2
graph = {
3
'1': ['2', '3', '4'],
4
'2': ['5', '6'],
5
'5': ['9', '10'],
6
'4': ['7', '8'],
7
'7': ['11', '12']
8
}
9
10
def bfs(graph, start, end):
11
# maintain a queue of paths
12
queue = []
13
# push the first path into the queue
14
queue.append([start])
15
while queue:
16
# get the first path from the queue
17
path = queue.pop(0)
18
# get the last node from the path
19
node = path[-1]
20
# path found
21
if node == end:
22
return path
23
# enumerate all adjacent nodes, construct a
24
# new path and push it into the queue
25
for adjacent in graph.get(node, []):
26
new_path = list(path)
27
new_path.append(adjacent)
28
queue.append(new_path)
29
30
print bfs(graph, '1', '11')
31
This prints: ['1', '4', '7', '11']
Another approach would be maintaining a mapping from each node to its parent, and when inspecting the adjacent node, record its parent. When the search is done, simply backtrace according the parent mapping.
JavaScript
1
31
31
1
graph = {
2
'1': ['2', '3', '4'],
3
'2': ['5', '6'],
4
'5': ['9', '10'],
5
'4': ['7', '8'],
6
'7': ['11', '12']
7
}
8
9
def backtrace(parent, start, end):
10
path = [end]
11
while path[-1] != start:
12
path.append(parent[path[-1]])
13
path.reverse()
14
return path
15
16
17
def bfs(graph, start, end):
18
parent = {}
19
queue = []
20
queue.append(start)
21
while queue:
22
node = queue.pop(0)
23
if node == end:
24
return backtrace(parent, start, end)
25
for adjacent in graph.get(node, []):
26
if node not in queue :
27
parent[adjacent] = node # <<<<< record its parent
28
queue.append(adjacent)
29
30
print bfs(graph, '1', '11')
31
The above codes are based on the assumption that there’s no cycles.