Frog Jump

http://www.lintcode.com/zh-cn/problem/frog-jump/

package com.LintCode.FrogJump;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution {
    public boolean canCross(int[] stones) {
        Map> map = new HashMap<>();
//        key是unit,value表示跳到这个unit用了几步
        for (int i = 0; i < stones.length; i++) {
//            只初始化这几个unit,其它的没有意义
            map.put(stones[i], new HashSet());
        }
        map.get(0).add(0);
        int target = stones[stones.length - 1];
        for (int i = 0; i < stones.length; i++) {
            int unit = stones[i];
//            得到当前所在的unit上
//            遍历可以跳到它的步数
            for (int step : map.get(unit)) {
//                可以向后跳的三种情况
                if (unit + step == target || unit + step - 1 == target || unit + step + 1 == target) {
                    return true;
                }
                process(map, unit, step - 1);
                process(map, unit, step);
                process(map, unit, step + 1);
            }
        }
        return false;
    }

    private void process(Map> map, int unit, int step) {
        int nextUnit = unit + step;
        if (map.containsKey(nextUnit) && nextUnit > unit) {
            map.get(nextUnit).add(step);
        }
    }
}

你可能感兴趣的:(Frog Jump)