LeetCode: 865. Shortest Path to Get All Keys

LeetCode: 865. 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.

解题思路 —— DFS + BFS

DFS 遍历顺序, BFS 遍历最近距离

AC 代码

class Solution {
private:
    // 返回距离 (x, y) 下一个 key 的位置
    pair<int, int> BFS(const vector<string>& grid, int x, int y, 
                       string keysSeached, char curKey, int& len)
    {
        if(x < 0 || y < 0 || x >= grid.size() || y >= grid[x].size())
        {
            return {-1, -1};
        }

        // 标记走过的路径
        vector<string> gridFlag(grid);
        gridFlag[x][y] = '#';

        queue<pair<int, int>> que;
        que.push({x, y});
        que.push({-1, -1});

        static int dirs[][2] = {{0,1}, {1, 0}, {0, -1}, {-1, 0}};
        while(!que.empty())
        {
            int curX = que.front().first;
            int curY = que.front().second;
            que.pop();

            if(curX == -1 && que.empty())
            {
                continue;
            }
            else if(curX == -1 && !que.empty())
            {
                que.push({-1, -1});
                ++len;
                continue;
            }

            for(int i = 0; i < 4; ++i)
            {
                int tx = curX + dirs[i][0];
                int ty = curY + dirs[i][1];

                // 越界
                if(tx < 0 || ty < 0 || tx >= grid.size() || ty >= grid[x].size())
                {
                    continue;
                }
                // 障碍
                if(gridFlag[tx][ty] == '#')
                {
                    continue;
                }
                // 锁 + 没有对应的 key
                if(isupper(gridFlag[tx][ty]) && 
                   keysSeached.find(tolower(gridFlag[tx][ty])) == keysSeached.npos)
                {
                    continue;
                }

                // 当前的 key
                if(gridFlag[tx][ty] == curKey && 
                   keysSeached.find(gridFlag[tx][ty]) == keysSeached.npos)
                {
                    return {tx, ty};
                }

                // 锁+有对应的 key,起点`@`, 路 `.`,处理过的key
                gridFlag[tx][ty] = '#';
                que.push({tx, ty});
            }
        }

        return {-1, -1};
    }

    // 返回距离
    int DFS(const vector<string>& grid, int x, int y, 
            string keysSeached, string keysSeaching)
    {
        if(x < 0 || y < 0 || x >= grid.size() || y >= grid[x].size())
        {
            return -1;
        }
        if(keysSeaching.empty())
        {
            return 0;
        }

        int ans = -1;
        for(int i = 0; i < keysSeaching.size(); ++i)
        {
            int nextLen = 1;
            pair<int, int> nextPos = BFS(grid, x, y, keysSeached, keysSeaching[i], nextLen);
            if(nextPos.first == -1) continue;
            string keysSeachedRef(keysSeached), keysSeachingRef(keysSeaching);
            keysSeachedRef.push_back(grid[nextPos.first][nextPos.second]);
            keysSeachingRef.erase(keysSeaching.find(grid[nextPos.first][nextPos.second]), 1);

            int ret = DFS(grid, nextPos.first, nextPos.second, keysSeachedRef, keysSeachingRef);

            if(ret == -1) continue;
            if(ans == -1 || ans > ret+nextLen) ans = ret + nextLen;
        }

        return ans;
    }
public:
    // DFS + BFS search solution
    int shortestPathAllKeys(vector<string>& grid) {
        bool ans = -1;
        pair<int, int> startPos;
        string keys;

        for(int i = 0; i < grid.size(); ++i)
        {
            for(int j = 0; j < grid[i].size(); ++j)
            {
                if(grid[i][j] == '@')
                {
                    startPos = {i, j};
                }

                if(islower(grid[i][j]))
                {
                    keys.push_back(grid[i][j]);
                }
            }
        }

        return DFS(grid, startPos.first, startPos.second, "", keys);
    }
};
全部评论

相关推荐

小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
Java大菜狗:纯纯招黑奴,一天还不到两百那么多要求,还不迟到早退,以为啥啊,给一点工资做一堆活,还以不拖欠员工工资为荣,这是什么值得骄傲的事情吗,纯纯***公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务