?LeetCode刷題實(shí)戰(zhàn)499:迷宮III
示例? ? ? ? ? ? ? ? ? ? ? ? ?


解題
class?Solution?{
public:
????string?findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole)?{
????????int?m = maze.size(), n = maze[0].size();
????????vector<vector<int>> dists(m, vector<int>(n, INT_MAX));
????????vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
????????vector<char> way{'l','u','r','d'};
????????queueint, int>> q;
????????unordered_map<int, string> u;
????????dists[ball[0]][ball[1]] = 0;
????????q.push({ball[0], ball[1]});
????????while?(!q.empty()) {
????????????auto?t = q.front(); q.pop();
????????????for?(int?i = 0; i < 4; ++i) {
????????????????int?x = t.first, y = t.second, dist = dists[x][y];
????????????????string?path = u[x * n + y];
????????????????while?(x >= 0?&& x < m && y >= 0?&& y < n && maze[x][y] == 0?&& (x != hole[0] || y != hole[1])) {
????????????????????x += dirs[i][0]; y += dirs[i][1]; ++dist;
????????????????}
????????????????if?(x != hole[0] || y != hole[1]) {
????????????????????x -= dirs[i][0]; y -= dirs[i][1]; --dist;
????????????????}
????????????????path.push_back(way[i]);
????????????????if?(dists[x][y] > dist) {
????????????????????dists[x][y] = dist;
????????????????????u[x * n + y] = path;
????????????????????if?(x != hole[0] || y != hole[1]) q.push({x, y});
????????????????} else?if?(dists[x][y] == dist && u[x * n + y].compare(path) > 0) {
????????????????????u[x * n + y] = path;
????????????????????if?(x != hole[0] || y != hole[1]) q.push({x, y});
????????????????}
????????????}
????????}
????????string?res = u[hole[0] * n + hole[1]];
????????return?res.empty() ? "impossible"?: res;
????}
};
LeetCode1-480題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)481:神奇字符串
LeetCode刷題實(shí)戰(zhàn)482:密鑰格式化
LeetCode刷題實(shí)戰(zhàn)483:最小好進(jìn)制
LeetCode刷題實(shí)戰(zhàn)484:尋找排列
LeetCode刷題實(shí)戰(zhàn)485:最大連續(xù) 1 的個(gè)數(shù)
LeetCode刷題實(shí)戰(zhàn)486:預(yù)測(cè)贏家
LeetCode刷題實(shí)戰(zhàn)487:最大連續(xù)1的個(gè)數(shù) II
LeetCode刷題實(shí)戰(zhàn)488:祖瑪游戲
LeetCode刷題實(shí)戰(zhàn)489:掃地機(jī)器人
LeetCode刷題實(shí)戰(zhàn)491:遞增子序列
LeetCode刷題實(shí)戰(zhàn)492:構(gòu)造矩形
LeetCode刷題實(shí)戰(zhàn)493:翻轉(zhuǎn)對(duì)
LeetCode刷題實(shí)戰(zhàn)494:目標(biāo)和
LeetCode刷題實(shí)戰(zhàn)495:提莫攻擊
LeetCode刷題實(shí)戰(zhàn)496:下一個(gè)更大元素 I
LeetCode刷題實(shí)戰(zhàn)497:非重疊矩形中的隨機(jī)點(diǎn)
LeetCode刷題實(shí)戰(zhàn)498:對(duì)角線遍歷
