Frog Jump

A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.

If the frog's last jump waskunits, then its next jump must be eitherk- 1,k, ork+ 1 units. Note that the frog can only jump in the forward direction.

public class Solution {

    Map<Integer, Integer> map = new HashMap<>();
    Set<String>       visited = new HashSet<>();
    int n;

    public boolean canCross(int[] stones) {

        n = stones.length;

        if(n == 0) return true;
        if(stones[1] > 1) return false;

        for(int i = 0; i < n; i ++)
            map.put(stones[i], i);

        return dfs(stones, 1, 1);
    }

    public boolean dfs(int[] stones, int start, int step) {

        if(visited.contains(start +" "+ step))
            return false;

        if(start >= n - 1)
            return start == n - 1;

        if(step - 1 > 0 && map.containsKey(stones[start] + step - 1) && 
                           dfs(stones, map.get(stones[start] + step - 1), step - 1))
            return true;
        if(map.containsKey(stones[start] + step) && 
                           dfs(stones, map.get(stones[start] + step), step))
            return true;
        if(step + 1 > 0 && map.containsKey(stones[start] + step + 1) && 
                           dfs(stones, map.get(stones[start] + step + 1), step + 1))
            return true;

        visited.add(start +" "+ step);
        return false;

    }
}

results matching ""

    No results matching ""