1. Description
2. Solutions
As soon as I saw this question, I thought it was similar to the minimal spanning tree. We should use the greedy algorithm. The idea of the greedy algorithm is as follows:
Start from the start string and find the set S1 of the string produced by a transformation. If the set S1 contains an end string, the search ends. Otherwise, search for the S2 set of strings that can be reached in two steps, and determine whether there is an end string in the string set that can be reached in two steps, and so on, and finally find the shortest path. In addition, you must set a separate data structure for path saving,
The final algorithm is described as follows (Minimum Spanning Tree of the class ):
So we have the following code:
After submitting online judge, the small data set is okay, but the big data set is TLE. After analysis, the process of finding nextStep from curStep is too time-consuming. I am O (N2) the result is as follows:
|
|
The results came out with a wonderful moment:
In addition, there is room for improvement in the method of output results. The path in the program is actually such a graph and actually an adjacent table.
My algorithm starts from the start to the end to find the end. When the last node to be searched is not the end, it is actually invalid (and the proportion is large ), so we can reverse the above image, and then start reverse search from the end to change the space for time.