Problem: given an undirected graph G, a subset H of the vertex set V, (i.e. H is a subset of V) and a starting vertex s (s is in V).
Design an algorithm that finds the lengths of the shortest paths from s to all vertices such that the paths don’t go through any intermediate vertex in H (meaning that you can end at a vertex in H but you cannot go through any vertex in H.) (If no such path exists then set the length to ∞. All edges are the same length.)
(The output of the algorithm should be an array similar to the dist array of BFS and Dijkstra’s.)
There is a straightforward way to solve this:
V - H
, i.e. all nodes except those inH
. Let the output bedist
.i
inH
, the shortest path will be of lengthmin {dist[j] + w[i][j]}
, wheremin
is applied across nodesj
inV-H
(can be made efficient if we have an adjacency list instead of matrix).So basically, with Dijkstra, find the shortest paths to nodes not in
H
. Then, the shortest path to nodes inH
is simply the shortest extension from a node inV-H
to itself. (And for nodes inH
that are not directly connected toV-H
, they'd have ∞ as question states).Noticed per @jrook's comment that you mentioned all edges are of same length. Then BFS can be used instead of Dijkstra's as well.
Another solution is running BFS on a modified version of the graph:
H
among themselves.V-H
andH
directed, with the direction being fromV-H
toH
.V-H
) directed by adding a directed edge in both directions.In this modified and directed graph, you can apply BFS or Dijkstra to find the shortest paths of desired condition.