Editorial for DMOPC '20 Contest 5 P3 - Bottom Row
Submitting an official solution before solving the problem yourself is a bannable offence.
A simple BFS from to is sufficient for this subtask. To reconstruct the lexicographically smallest shortest path, simply backtrack greedily, taking the lexicographically least character at each cell.
For the full solution, we will need to make a couple of observations.
Either a path does not exist, or it will only move up or to the right. This can be proven in many ways by banking on the fact that every row and column has at most one blocked square, and will be left as a short exercise for the reader.
Diagonal chains of blocked cells that go from top-left to bottom-right can be represented by the smallest square that encloses it. Any path that passes through such a square can be easily replaced by a shorter path, so an optimal path will never pass through these squares.
There is some connected region in the bottom right of the grid for which we cannot reach by only moving up or to the right (and thus, paths which cross through this region cannot be optimal). We may construct this region by taking the "shadow" cast by the blocked cell on column (if it exists), propagating the shadow leftward through other blocked cells and bounding squares from observation . It is easy to see that any cell contained in this shadowed region cannot reach by only moving up or to the right.
With these observations, we can simply block out the regions from observations and and then greedily construct a path (if it exists), taking
U whenever possible since it is lexicographically smaller. To prevent degrading to time complexity from maintaining these blocked regions, notice that we only have to maintain their outlines, which is on the order of . Depending on implementation, an extra log factor may be required.
Time Complexity: or