864.Shortest-Path-to-Get-All-Keys

864. Shortest Path to Get All Keys

题目地址

https://leetcode.com/problems/shortest-path-to-get-all-keys/

题目描述

We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, and ("A", "B", ...) are locks.

We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions.  We cannot walk outside the grid, or walk into a wall.  If we walk over a key, we pick it up.  We can't walk over a lock unless we have the 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's impossible, return -1.

Example 1:
Input: ["@.a.#","###.#","b.A.B"]
Output: 8

Example 2:
Input: ["@..aA","..B#.","....b"]
Output: 6

Note:
1 <= grid.length <= 30
1 <= grid[0].length <= 30
grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'
The number of keys is in [1, 6].  Each key has a different letter and opens exactly one lock.

代码

Approach #1 BFS

Time: O(mn2^k) && Space: O(1)

class Solution {

    class State {
        int x;
        int y;
        int key;
        public State(int x, int y, int key) {
            this.x = x;
            this.y = y;
            this.key = key;
        }
    }

    int[][] dirs = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    public int shortestPathAllKeys(String[] grid) {
        int x = 0;
        int y = 0;
        int n = grid.length;
        int m = grid[0].length(); 
        int keyCount = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                char c = grid[i].charAt(j);
                if (c == '@') {
                    x = i;
                    y = j;
                }

                 if (c >= 'a' && c <= 'f') {
                     keyCount = Math.max(keyCount, c - 'a' + 1);
                 }    

            }
        }

        HashSet<String> visited = new HashSet();
        Queue<State> queue = new LinkedList();
        queue.add(new State(x, y, 0));
        visited.add(x + " " + y + " " + 0);
        int step = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int k = 0; k < size; k++) {
                State cur = queue.poll();
                if (cur.key == (1 << keyCount) - 1) return step;
                for (int[] dir: dirs) {
                    int i = cur.x + dir[0];
                    int j = cur.y + dir[1];

                    if (i < 0 || i >= n || j < 0 || j >= m) {
                        continue;
                    }

                    char c = grid[i].charAt(j);
                    int key = cur.key;
                    if (c == '#') {
                        continue;
                    }

                    if (c >= 'a' && c <= 'f') {
                        key |=  (1 << (c - 'a'));
                    }

                    if (c >= 'A' && c <= 'F' 
                        && (cur.key >> (c  - 'A') & 1) == 0) {
                        continue;
                    }

                    if (!visited.contains(i + " " + j + " " + key)) {
                        queue.add(new State(i, j, key));
                        visited.add(i + " " + j + " " + key);
                    }
                }
            }
            step++;
        }


        return -1;
    }
}

Last updated