Editorial for WC '17 Contest 2 S2 - Don't Follow the Lights


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
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 \mathcal O(RC) nodes in the graph, and at most four outgoing edges from each node, meaning that there are also \mathcal O(RC) edges in total. The time complexity of BFS is then \mathcal O(RC), 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 (r, c) (in row r and column c), it's possible to move upwards to cell (r-1, c) if r > 1, neither of those two cells contain a torch, and there are fewer than two torches in all of cells (1 \dots (r-2), c) (or, equivalently, in cells (1 \dots r, c)). Similar conditions apply to moving downwards, leftwards, and rightwards from cell (r, c).

The most direct method of finding all valid moves which satisfy the above conditions is to consider each cell (r, c) independently. A simple check for whether there are fewer than two torches in cells (1 \dots r, c) takes \mathcal O(R) time. The corresponding check for torches below cell (r, c) also takes \mathcal O(R) time, while the checks for torches to the left and right each take \mathcal O(C) time. Therefore, this approach for constructing the graph takes \mathcal O(RC(R+C)) time in total, which isn't efficient enough to receive full marks.

The time complexity of the above process can be improved to \mathcal O(RC) by observing that, for example, the number of torches in cells (1 \dots r, c) can be computed in \mathcal O(1) if we already have the number of torches in cells (1 \dots (r-1), c). If we fix c and iterate r upwards from 1 to R, while maintaining the number of torches encountered so far in that column (in other words, the number of torches in cells (1 \dots r, c)), then we can find all of the valid upwards moves in that column in just \mathcal O(R) time. This can then be repeated for all C columns, and a similar process can be repeated for the other three directions.


Comments

There are no comments at the moment.