獲取所有鑰匙的最短路徑

Iter-moon發表於2024-07-22
class Solution {
public:
    int shortestPathAllKeys(vector<string>& a) {
        // 上 右 下 左
        struct node {
            int x, y, w;
        };
        const int N = 34, K = 6;
        int dirs[5] = {-1, 0, 1, 0, -1}; 
        bool vis[N][N][1 << K] = {0};
        int key = 0, n = a.size(), m = a[0].size(); 
        queue <node> q;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (a[i][j] == '@') {
                    q.push({i, j, 0});
                }
                if (a[i][j] >= 'a' && a[i][j] <= 'f') {
                    key |= 1 << (a[i][j] - 'a');
                }
            }
        } 
        int lever = 0;
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                auto [x, y, w] = q.front(); 
                q.pop(); 
                for (int d = 0; d < 4; d++) {
                    int dx = x + dirs[d];
                    int dy = y + dirs[d + 1]; 
                    if (dx < 0 || dx >= n || dy < 0 || dy >= m || a[dx][dy] == '#') {
                        continue; 
                    }  
                    int ds = w;  
                    if (a[dx][dy] >= 'A' && a[dx][dy] <= 'F') {
                        if ((ds & (1 << (a[dx][dy] - 'A'))) == 0) {
                            continue; 
                        }
                    } 
                    if (a[dx][dy] >= 'a' && a[dx][dy] <= 'f') {
                        ds |= (1 << (a[dx][dy] - 'a'));
                    } 
                    if (ds == key) {
                        return lever + 1;
                    } 
                    if (!vis[dx][dy][ds]) {
                        vis[dx][dy][ds] = 1;
                        q.push({dx, dy, ds});
                    }
                }
            }
            lever++; 
        }
        return -1;
    }
};

  

相關文章