Editorial for COCI '12 Contest 5 #3 Totem


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.

Since the problem in this task is finding the shortest path, in number of steps, from the beginning to some position, we can obviously use the breadth-first search (BFS) algorithm. However, we first need to derive a graph corresponding to the problem that we can apply BFS to. In this graph, nodes will correspond to tiles, and edges will exist between some two nodes if it is possible to step directly from one corresponding tile to the other.

The graph can be constructed in the following way. The numbers chiseled into tiles can be read into a matrix with N rows and 2N columns, where squares not covered by a tile (the first and last cells of even-numbered rows, numbered from 1) can be set to 0. Another matrix of the same dimensions can be used to store the corresponding tile index for each square. Now we can, for each square, iterate over its four neighbouring squares and add an edge between the current square's and the neighbouring square's tile iff the cells have different tile indexes (so that we don't add an edge from a tile to itself) and the squares have equal numbers (the condition of stepping from one tile to the next). The complexity of this part of the solution is \mathcal O(N^2) since we have processed each of the 2N^2 squares once (as the current square) plus at most four times (as the neighbouring square).

Now that we have constructed the graph, we can apply breadth-first search starting from the first tile. For each tile, we need to keep track not only of the distance to the starting tile, but also of the previous tile (the tile that we stepped directly from when moving to the current tile), so that we can reconstruct the path later. The complexity of this part of the solution is also \mathcal O(N^2), since BFS processes each of the N^2 nodes once (as the current node) plus at most six times (since there are at most six neighbouring tiles).

Finally, we need to find the tile with the largest index that we have reached and, going backwards using the previous nodes stored during BFS, reconstruct the shortest path by storing the traversed tiles' indexes, from end to start, in an array. The final solution is the length of the obtained array and the array itself, output in reverse. The complexity of this part of the solution is again \mathcal O(N^2) because the shortest path can contain each of the N^2 tiles at most once.


Comments

There are no comments at the moment.