Shortest Path to Get All Keys

You are given an m x n grid grid where:

  • '.' is an empty cell.
  • '#' is a wall.
  • '@' is the starting point.
  • Lowercase letters represent keys.
  • Uppercase letters represent locks.

You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.

If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.

For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.

Return the lowest number of moves to acquire all keys. If it is impossible, return -1.

 

Example 1:

Input: grid = ["@.a.#","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.

 思路:这题跟Shortest Path Visiting All Nodes

是一模一样的题目,就是pos会重复visit,但是每次visite的状态是不一样的,收集的key是不一样的,所以用(i, j, state)来表示visit,state是用1<< (key - 'a)来表示的,代表收集了多少个key;

class Solution {
    public int shortestPathAllKeys(String[] grid) {
        int m = grid.length;
        int n = grid[0].length();
        int finalstate = 0;
        int startX = -1; int startY = -1;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                char c = grid[i].charAt(j);
                if(c == '@') {
                    startX = i;
                    startY = j;
                } else if('a' <= c && c <= 'f') {
                    finalstate |= 1 << (c - 'a');
                }
            }
        }
        
        Queue<int[]> queue = new LinkedList<>();
        HashSet<String> visited = new HashSet<>();
        queue.offer(new int[] {startX, startY, 0});
        visited.add(startX + " " + startY + " " + 0);
        
        int[][] dirs = new int[][] {{0,-1},{0,1},{1,0},{-1,0}};
        
        int step = 0;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                int[] node = queue.poll();
                int x = node[0];
                int y = node[1];
                int curstate = node[2];
                if(curstate == finalstate) {
                    return step;
                }
                for(int[] dir: dirs) {
                    int nextstate = curstate;
                    int nx = x + dir[0];
                    int ny = y + dir[1];
                    if(0 <= nx && nx < m && 0 <= ny && ny < n && grid[nx].charAt(ny) != '#') {
                        char c = grid[nx].charAt(ny);
                        // collect keys;
                        if('a' <= c && c <= 'f') {
                            nextstate |= 1 << (c - 'a');
                        }
                        // if next cube is lock, but i don't have keys, i still can not go;
                        if('A' <= c && c <= 'Z' && ((nextstate >> (c - 'A')) & 1) == 0) {
                            continue;
                        }
                        if(!visited.contains(nx + " "+ ny + " " + nextstate)) {
                            visited.add(nx + " "+ ny + " " + nextstate);
                            queue.offer(new int[] {nx, ny, nextstate});
                        }
                    }
                }
            }
            step++;
        }
        return -1;
    }
}

 

All-Pairs Shortest Path问题是指在一个带权有向图中,求出任意两个节点之间的最短路径。解决这个问题的算法称为All-Pairs Shortest Path算法。 常用的All-Pairs Shortest Path算法有Floyd-Warshall算法和Johnson算法。 Floyd-Warshall算法的基本思想是动态规划。用dist[i][j]表示从节点i到节点j的最短路径长度,用k表示中间节点,则有状态转移方程: ``` dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) ``` 其中,dist[i][j]的初始值为节点i到节点j的边权,如果i和j之间没有边,则为正无穷。算法的核心是对k从1到n的循环,依次更新dist[i][j]的值,最终得到所有节点之间的最短路径长度。 Floyd-Warshall算法的时间复杂度为O(n^3),其中n为节点数,主要时间花费在三层循环上,实际应用中可以通过空间换时间的方式优化算法。 Johnson算法的基本思想是通过引入一个虚拟节点,并将其与所有节点之间的边权设为0,将问题转化为带权有向图中的单源最短路径问题。然后使用Bellman-Ford算法求出虚拟节点到其它所有节点的最短路径长度,再用求最短路径时的松弛操作更新所有边的边权,将问题转化为带权有向图中的多源最短路径问题。最后使用Dijkstra算法求出所有节点之间的最短路径长度。 Johnson算法的时间复杂度为O(n^2logn+m),其中n为节点数,m为边数,主要时间花费在Bellman-Ford算法和Dijkstra算法上,实际应用中可以通过优化数据结构等方式优化算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值