895. Shortest Path to Get All Keys

  • Difficulty: Hard

  • Topics: Heap, Breadth-first Search

  • Similar Questions:

Problem:

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.
</div>

Solutions:

using namespace std;

class Solution {
public:

    struct Status {
        int x;
        int y;
        int keys;

        Status(int x, int y, int keys) {
            this->x = x;
            this->y = y;
            this->keys = keys;
        }

        bool operator<(const Status& other) const {
            if (x != other.x) {
                return x < other.x;
            }

            if (y != other.y) {
                return y < other.y;
            }

            return keys < other.keys;
        }
    };


    inline bool isKey(char c) {
        return c >= 'a' && c <= 'z';
    }

    inline bool isLock(char c) {
        return c >= 'A' && c <= 'Z';
    }


    int shortestPathAllKeys(vector<string>& grid) {
        int keyCount = 0;
        pair<int, int> startPoint;
        int m = grid.size();
        if (m == 0) return 0;
        int n = grid[0].length();
        if (n == 0) return 0;

        for (int x = 0; x < m; ++x) {
            for (int y = 0; y < n; ++y) {
                if (grid[x][y] == '@') {
                    startPoint = {x, y};
                } else if (isKey(grid[x][y])) {
                    ++keyCount;
                }
            }
        }

        if (keyCount == 0)  return 0;
        queue<Status> q;
        set<Status> visited;
        q.push({startPoint.first, startPoint.second, 0});
        int steps = 0;
        int allKeys = (1 << keyCount) - 1;

        while (!q.empty()) {
            int size = q.size(); // The reason for my mistake is that I first define "int n = q.size()" !!! n outside this code block is shadowed! 
            for (int i = 0; i < size; ++i) {
                Status s = q.front(); q.pop();
                if (s.x < 0 || s.x >= m || s.y < 0 || s.y >= n || grid[s.x][s.y] == '#') continue;
                if (visited.count(s) > 0)   continue;
                visited.insert(s);

                if (isKey(grid[s.x][s.y])) {
                    s.keys = ((s.keys) | (1 << (grid[s.x][s.y] - 'a')));
                } else if (isLock(grid[s.x][s.y])) {
                    if (((s.keys >> (grid[s.x][s.y] - 'A')) & 1) != 1) {
                        continue;
                    }
                }
                visited.insert(s);

                if (s.keys == allKeys)  return steps;

                q.push({s.x + 1, s.y, s.keys});
                q.push({s.x - 1, s.y, s.keys});
                q.push({s.x, s.y + 1, s.keys});
                q.push({s.x, s.y - 1, s.keys});
            }
            ++steps;
        }

        return -1;
    }
};

results matching ""

    No results matching ""