Search This Blog

Tuesday, December 18, 2012

LeetCode:Jump Game

Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

public class Solution {
    public boolean canJump(int[] A) {
        // Start typing your Java solution below
        // DO NOT write main() function
        assert (A!=null && A.length>0);
        boolean [] visited = new boolean[A.length];
        
        Stack<Integer> toVisit = new Stack<Integer>();
        toVisit.push(A.length-1);
        
        while(!toVisit.isEmpty()){
            int cur = toVisit.pop();
            visited[cur]=true;
            if(cur==0) return true;
            for(int i=0;i<A.length;i++){
                if(i!=cur && !visited[i] && i+A[i]>=cur && i-A[i]<=cur){
                    toVisit.push(i);
                }
            }
        }
        return false;
    }
}

No comments: