简体   繁体   中英

Find path between 2 vertices with x red vertices

I've tried a couple of approaches and they all ended in a dead end. The question:

Given a G=(V,E) a directed unweighted graph in which every vertex is colored red or blue. Let there be vertices s and t from V. Describe an algorithm that would find a path between s and t which would hold the least red vertices. Explain the algorithm, prove it and show its complexity.

I've thought of 2 approaches and discarded both:

  1. Use an adjacency list sorted by colors (blue first red last) and run a DFS - bad idea
  2. Set the weight of each edge from a red vertex to 2 and blues to 1 and run Dijkstra - found a counterexample

I would really be happy to get some help with the right direction. I prefer NOT to get full answers but rather hits/tips.

Consider setting weight=1 for any edge that goes to a red vertex. Then show that the cost of a path from s with n red vertices is either n or n-1 , depending on the color of s.

Well I've found an answer to this question, not me but a friend of mine after I showed him the weighted way to do it.

Instead of using one queue in the BFS algorithm we will use 2 queues: one for the blue vertices and one for the red vertices.

we check what color is S and add it to the right queue, as long as queue of the blue vertices is not empty we dequeue from it and continue the regular BFS if we encounter a red vertex we enqueue it to the red queue and if we find a blue vertex we enqueue it to the blue queue. if the blue queue is empty we dequeue from the red queue.

eventually the array pi[|V|] will hold a backwards representation to vertex v with least of red vertices.

since there is no real change to the BFS algorithm and not to it's data structures the proof of correctness holds and the time complexity is O(|V|+|E|) as in BFS.

thanks for the help guys!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM