1345. Jump Game IV

52 阅读1分钟

image.png

方法:建图,bfs求到arr末尾数字的最短路径

  • 根据题目描述,我们可以把给定数组整理成一个无向图,数组中相邻的元素或者元素值相同的元素相连即可。
  • 这就等价于求从arr[0]~arr[n-1]最短路径长度,容易想到BFS

image.png

class Solution {
    public int minJumps(int[] arr) {
        // 存储某个值对应有哪些索引。
        // 只存相等的,吗的,只能这么写,不能存邻居
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            List<Integer> list = map.getOrDefault(arr[i], new ArrayList<>());
            list.add(i);
            map.put(arr[i], list);
        }

        // 存储索引即可
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);

        // 被访问过
        boolean[] visited = new boolean[arr.length];

        int step = 0;
        while (!queue.isEmpty()) {
            step++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int idx = queue.poll();
                // 到达arr中最后一个数了
                if (idx == arr.length - 1) {
                    return step - 1; // 注意
                }
                // 三种走法
                // 1. 到相等的位置
                if (map.containsKey(arr[idx])) {
                    for (int x : map.get(arr[idx])) {
                        if (!visited[x]) {
                            queue.offer(x);
                            visited[x] = true;
                        }
                    }
                    // 这个元素相连的都处理过了,后面再遍历到再处理肯定都已经访问过了
                    // 走回头路的代价总是大于第一次到达的
                    map.remove(arr[idx]);
                }

                // 2. 后退
                if (idx - 1 >= 0 && !visited[idx - 1]) {
                    queue.offer(idx - 1);
                    visited[idx - 1] = true;
                }
                // 3. 前进
                if (idx + 1 < arr.length && !visited[idx + 1]) {
                    queue.offer(idx + 1);
                    visited[idx + 1] = true;
                }
            }
        }
        return step;
    }
}