45

I'll throw in my two cents here. I believe my code is similar to others' in essence. However, I interpret my method as a simplified version of LEVEL-ORDER traversal, where the ith level contains the nodes that can be reached in as few as i steps (so if a node can be reached in, say, i, i+1 or i+2 steps, it should be included only in the ith level). As soon as we find that the last node appears in the current level, then the index of this level can be returned as the minimum number of jumps that is required to reach the last node.

The implementation is actually simpler than a regular level-order travesal: All the values are already stored in an array, so there is no need to maintain an extra queue. We only need to maintain two pointers: 'lo' and 'hi', representing the start and end of the queue, respectively. We process the 'top' element (i.e. 'lo') one at a time, and add its possible children on the next level to the end of the 'queue' by expanding 'hi'. When we detect that 'lo' is greater than the original 'hi'. it means that we have finished the current level, then we add one to the level index ('njump' in my code), and proceed to the next level.

To expand the queue, we do not need to know which values are the children of the 'lo' element exactly, we only care about what the queue would look like after its children are 'pushed' to the end. That is, the elements that can be reached from 'lo' with ONE jump ( < A[lo] + lo) AND has not been visited ( > hi). Therefore, the end of the queue after the expansion should be:

hi = max(hi, A[lo] + lo)

The following code is slightly more verbose than the most concise implementations previously posted, but I believe it better illustrates my interpretation of this problem.

int jump(int A[], int n) {
    int lo = 0, hi = 0;
    int njumps = 0;

    // Break from the loop as soon as we find that the last node is included in the queue
    while (hi < n - 1)  
    {
        int cur_hi = hi;
        while (lo <= cur_hi) // Process the current level.
        {
            hi = max(hi, A[lo] + lo); // Expand the current queue.
            lo ++; // Get ready to process the next element
        }
        njumps++; // Increase level index after a level is processed
    }
    return njumps;
}

This code, of course, does not consider the case when the last node cannot be reached (e.g. '[3 2 1 0 4]'), but it can be trivially modified to handle this case: If in a certain iteration, the 'queue' becomes empty ('lo == hi', indicating the traversal is completed), but we still have not reached the last node. It means the last node simply cannot be reached. We can do whatever error handling we would like to when this happens. Thus, this idea can also be applied to 'Jump Game I'. Only in that case, we don't even need to use LEVEL-ORDER travesal; a simple BFS would suffice.

posted @ 2015-10-24 15:07  曾可爱  阅读(134)  评论(0编辑  收藏  举报