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. 1 <= grid.length <= 30
  2. 1 <= grid[0].length <= 30
  3. grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'
  4. The number of keys is in [1, 6].  Each key has a different letter and opens exactly one lock.

Solution:

class Solution {
    public int shortestPathAllKeys(String[] grid) {
        Deque<Pair<Integer, Set<Character>>> queue = new ArrayDeque();
        int m = grid.length, n = grid[0].length();
        char[][] graph = new char[m][n];
        for (int i = 0; i < m; i ++) {
            graph[i] = grid[i].toCharArray();
        }
        int numKeys = 0;
        for (int i = 0; i < m; i ++) {
            for (int j = 0; j < n; j ++) {
                if (graph[i][j] == '@') {
                    queue.offer(new Pair(i * n + j, new HashSet<Character>()));
                }
                if (graph[i][j] >= 'a' && graph[i][j] <= 'z') {
                    numKeys ++;
                }
            }
        }
        int step = 0;
        int[] dx = {-1, 0, 0, 1};
        int[] dy = {0, -1, 1, 0};
        Set<Pair<Integer, Set<Character>>> visited = new HashSet();
        visited.add(queue.peek());
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i ++) {
                Pair<Integer, Set<Character>> curr = queue.poll();
                Set<Character> keys = curr.getValue();
                if (keys.size() == numKeys) return step;
                int x = curr.getKey() / n;
                int y = curr.getKey() % n;
                for (int k = 0; k < 4; k ++) {
                    int nx = x + dx[k];
                    int ny = y + dy[k];
                    if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                        Pair<Integer, Set<Character>> next = null;
                        if (graph[nx][ny] == '.' || graph[nx][ny] == '@') {
                            next = new Pair(nx * n + ny, keys);
                        } else if (graph[nx][ny] >= 'a' && graph[nx][ny] <= 'z') {
                            Set<Character> newkeys = new HashSet(keys);
                            newkeys.add(graph[nx][ny]);
                            next = new Pair(nx * n + ny, newkeys);
                        } else if (curr.getValue().contains(Character.toLowerCase(graph[nx][ny]))) {
                            next = new Pair(nx * n + ny, keys);
                        }
                        if (next != null && visited.add(next)) {
                            queue.offer(next);
                        }
                    }
                }
            }
            step ++;
        }
        return -1;
    }
}