0

Problem

There are n locations ( vertices ) in a city, which are connected through streets of length 1 ( edge length = 1 ). Some of the locations have petrol stations ( colored vertex ) while others don't. People at locations with no petrol stations, go to their closest petrol station. What is the maximum distance one may have to travel to find a petrol station?

My solution

I have been able to come up with a BFS approach, where I initialize the maximum distance for the non-petrol location to max_int, then I do a BFS from every petrol location and keep updating the distances of the non-petrol location. However, I feel like there must be a more optimal solution to this problem.

Taimoor Ali
  • 158
  • 1
  • 7

1 Answers1

0
LOOP N over uncolored vertices
    SET D(N) = MAX INT
LOOP N over uncolored vertices
    BFS from N DO FOR each V reached
        IF V is colored 
            STOP BFS ( no need to search further )
        ELSE IF N-V distance less than D(N)
            D(V) = N-V distance
SET M = 0
LOOP N over uncolored vertices
   IF D(N) > M
      M = D(N)
OUTPUT M
ravenspoint
  • 19,093
  • 6
  • 57
  • 103