Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 1345. Jump Game IV #217

Open
Woodyiiiiiii opened this issue Mar 5, 2023 · 0 comments
Open

Leetcode 1345. Jump Game IV #217

Woodyiiiiiii opened this issue Mar 5, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题我还想着用DP,重点在如何解决i-1这个问题,难道要逆序DP吗?

无法推导了,说明DP不可行了。那就尝试另一种方法。

那么只能继续看题目条件了,重点是如何解决这套jump规则问题,而且还是在最少步数下跳到最后一个位置。

可以继续推导,可以发现,把数组每个元素看成一个点,跳跃规则就是边,那么这就是个图问题,所以可以从BFS/DFS来考虑,暴力穷举所有跳跃可能位置。

这种数组内用BFS/DFS的题也很多的,比如:

class Solution {
    public int minJumps(int[] arr) {
        int n = arr.length;
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < n; ++i) {
            map.computeIfAbsent(arr[i], x -> new ArrayList<>()).add(i);
        }
        boolean[] visited = new boolean[n];
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);
        visited[0] = true;
        int step = 0;
        while (!queue.isEmpty()) {
            int sz = queue.size();
            while (sz-- > 0) {
                int u = queue.poll();
                if (u == n - 1) {
                    return step;
                }
                if (u - 1 >= 0 && !visited[u - 1]) {
                    queue.offer(u - 1);
                    visited[u - 1] = true;
                }
                if (u + 1 < n && !visited[u + 1]) {
                    queue.offer(u + 1);
                    visited[u + 1] = true;
                }
                for (int v : map.get(arr[u])) {
                    if (!visited[v]) {
                        queue.offer(v);
                        visited[v] = true;
                    }
                }
                map.get(arr[u]).clear();
            }
            ++step;
        }
        return -1;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant