题目链接:1210. 穿过迷宫的最少移动次数
参考:还在 if-else?一个循环处理六种移动!
代码
class Solution {
private:
static constexpr int mov[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; // 下、右、旋转
public:
int minimumMoves(vector<vector<int>>& grid) {
int n = grid.size();
bool vis[n][n][2]; memset(vis, 0, sizeof(vis));
vis[0][0][0] = true;
vector<tuple<int, int, int>> q = {{0, 0, 0}}; // (x, y, s)—(x, y)表示蛇尾坐标,s表示蛇身的方向,s = 0为横,s = 1为竖;
for (int step = 1; !q.empty(); step ++ ) {
vector<tuple<int, int, int>> next;
for (const auto &[X, Y, S] : q) { // 遍历当前层的所有位置
for (const auto &d : mov) { // 尝试3种不同的走法
int x = X + d[0], y = Y + d[1], s = S ^ d[2]; // 下一步蛇尾
int x2 = x + s, y2 = y + (s ^ 1); // 下一步蛇头
if (x2 < n && y2 < n && !vis[x][y][s] &&
grid[x][y] == 0 && grid[x2][y2] == 0 && (d[2] == 0 || grid[x + 1][y + 1] == 0)) {
// 1、边界判断 2、蛇身障碍物判断 3、旋转时蛇尾对角是否有障碍物
if (x == n - 1 && y == n - 2) return step;
vis[x][y][s] = true;
next.emplace_back(x, y, s);
}
}
}
q = move(next);
}
return -1;
}
};