Reputation: 37
I have a problem very similar to https://leetcode.com/problems/jump-game-ii/description/.
Apart from discovering the minimum steps to reach the end, I need to retrieve the winning path array.
The winning path that is needed for my problem must satisfy the rule that given path A
like [0,2,4,7]
there are not any other paths with the same price (steps to the end, 3
in this case) whose nodes starting from the path's end has lower indexes.
The single step from i
to i+1
has not price equal to 1
but is 0 <= x <= 2^32-1
.
[0,2,4,5,7]
is the winner[0,1,4,6,7]
is not the winner because 6 > 5
at index 3
This has to work also in reverse:
[7,6,3,1,0]
is the winner[7,5,4,2,0]
is not the winner because 2 > 1
at index 3
Note that this rule is applied from right to left.
Clearly, I can produce all the paths with BFS and hence compare them but is there a more efficient way?
Upvotes: 0
Views: 61
Reputation: 181199
The winning path that is needed for my problem must satisfy the rule that given
path A
like[0,2,4,7]
there are not any other paths with the same price (steps to the end,3
in this case) whose nodes starting from the path's end has lower indexes.
I can produce all the paths with BFS and hence compare them but is there a more efficient way?
Yes.
Search backwards, from end to start, in BFS fashion. When you enqueue each node's unvisited successors, do it in increasing order by index. The first path you discover will then be the reverse of the path you're looking for.
Upvotes: 0