Editorial for COCI '12 Contest 5 #3 Totem
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
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
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
Comments