Reputation: 23
I have an un-directed graph 'G' and a set 'A' of nodes in the graph G
I'm struggling with finding an efficient algorithm that finds the the shortest paths from any node in the graph G to the closest node in the set 'A'
I thought about this: having a minimum distance array to all nodes, Running BFS algorithm on each node in set A and after BFS completion, update the array if a shorter path was found, this time complexity is O(k(n+m)) - which is a lot when as K grows, I was told there is a more efficient algorithm i can use. Please note, I'm only allowed to use BFS algorithm in this exercise
Upvotes: 2
Views: 175
Reputation: 82899
You really just need a single pass of your BFS algorithm if you start with all the nodes from A
in the initial queue.
(a, empty_path)
for each node a
in your A
setvisited
map, skip itvisited
with the given pathExample in Python:
# 2--0--1
# | |
# 3 4
graph = {0: [1, 2], 1: [0, 4], 2: [0, 3], 3: [2], 4: [1]}
A = [2, 0]
import collections
queue = collections.deque([(a, []) for a in A])
visited = {}
while queue:
cur, path = queue.popleft()
if cur in visited: continue
visited[cur] = path
for node in graph[cur]:
queue.append((node, [cur] + path))
print(visited)
# {2: [], 0: [], 3: [2], 1: [0], 4: [1, 0]}
Upvotes: 0
Reputation: 9085
Create an extra node that had edges to every node in 'A.' Run BFS from this extra node. The distance from every node to the closest node in 'A' is 1 less than the distance to this extra node.
Upvotes: 2