Editorial for WC '17 Contest 2 S2 - Don't Follow the Lights
Submitting an official solution before solving the problem yourself is a bannable offence.
We can represent the grid as a graph, with one node per cell, and an unweighted, directed edge for each valid move between pairs of cells. We then need to find the length of the shortest path from one node to another on this graph, which can be done with a standard application of Breadth First Search (BFS). There are nodes in the graph, and at most four outgoing edges from each node, meaning that there are also
edges in total. The time complexity of BFS is then
, which is fast enough.
Assuming familiarity with BFS, the trickiest part of the solution is efficiently determining the set of edges which exist in the graph in the first place. For a given cell (in row
and column
), it's possible to move upwards to cell
if
, neither of those two cells contain a torch, and there are fewer than two torches in all of cells
(or, equivalently, in cells
). Similar conditions apply to moving downwards, leftwards, and rightwards from cell
.
The most direct method of finding all valid moves which satisfy the above conditions is to consider each cell independently. A simple check for whether there are fewer than two torches in cells
takes
time. The corresponding check for torches below cell
also takes
time, while the checks for torches to the left and right each take
time. Therefore, this approach for constructing the graph takes
time in total, which isn't efficient enough to receive full marks.
The time complexity of the above process can be improved to by observing that, for example, the number of torches in cells
can be computed in
if we already have the number of torches in cells
. If we fix
and iterate
upwards from
to
, while maintaining the number of torches encountered so far in that column (in other words, the number of torches in cells
), then we can find all of the valid upwards moves in that column in just
time. This can then be repeated for all
columns, and a similar process can be repeated for the other three directions.
Comments