Here is a summary of the optimal solution ( O (N ^ 2) ) mentioned by IVlad and throwawayacct . For some reason their voice is not heard :)
Consider the NxN grid as a graph with nodes representing rooms and edges representing the doors between adjacent rooms. All ribs have a weight of 1. A set of U nodes is designated as βguarded roomsβ.
The idea is to use the BFS bypass, which starts with a new node connected to all protected rooms and scans the rooms in order of increasing distance from v0. Each time a node is visited, the number of steps that were taken to achieve it represents the distance from the guarded room, and it is guaranteed that it will be minimal due to the order of the extension of the path:
Add an artificial node v0 and connect it to all nodes in U Create a simple queue Q, that stores pairs <node, dist> Q.enqueue(<v0, -1>) Create a hash set S, that contains all visited nodes S.add(v0) while not Q.isEmpty() { pathTail := Q.dequeue() output distance pathTail.dist for node pathTail.node for all neighbours v of pathTail.node if not S.contains(v) Q.add(<v, pathTail.dist + 1>) S.add(pathTail.node) }
Difficulty analysis
Note that the graph is flat; therefore, we have | V | + | E | = O (| V |). Therefore, this BFS works in O (| V |) = O (N ^ 2) time.
The fact that we have a single weight for the ribs makes things simple; A uniform distance value is guaranteed in the queue. For example, using dijkstra, the edges can differ in their weight, so a priority queue is necessary, and this affects the time complexity. The same problem presented here, with different weights between rooms, would require O (NNlog N) time.
source share