1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
class Solution
{
public:
#define x first
#define y second
int snakesAndLadders(vector<vector<int>>& board)
{
int n = board.size();
// 记录编号与坐标的映射
std::vector<std::vector<int>> id(n, std::vector<int>(n));
using PII = std::pair<int, int>;
std::vector<PII> cord(n * n + 1);
// 生成棋盘编号与坐标的映射
int k = 1, direct = 0;
for (int i = n - 1; i >= 0; --i)
{
if (direct % 2 == 0)
{ // 从左到右
for (int j = 0; j < n; ++j)
{
id[i][j] = k;
cord[k] = {i, j};
++k;
}
}
else
{ // 从右到左
for (int j = n - 1; j >= 0; --j)
{
id[i][j] = k;
cord[k] = {i, j};
++k;
}
}
++ direct;
}
// BFS 寻找最短路径
std::queue<PII> q;
std::vector<std::vector<int>> dist(n, std::vector<int>(n, 1e9));
q.push({n - 1, 0}); // 从起点开始
dist[n - 1][0] = 0;
while (!q.empty())
{
PII t = q.front();
q.pop();
int k = id[t.x][t.y]; // 当前编号
if (k == n * n) // 到达终点
return dist[t.x][t.y];
for (int i = k + 1; i <= k + 6 && i <= n * n; ++i)
{
int x = cord[i].x, y = cord[i].y;
if (board[x][y] == -1)
{ // 无蛇无梯子
if (dist[x][y] > dist[t.x][t.y] + 1)
{
dist[x][y] = dist[t.x][t.y] + 1;
q.push({x, y});
}
}
else
{ // 存在蛇或梯子
int ladder = board[x][y];
x = cord[ladder].x, y = cord[ladder].y;
if (dist[x][y] > dist[t.x][t.y] + 1)
{
dist[x][y] = dist[t.x][t.y] + 1;
q.push({x, y});
}
}
}
}
return -1; // 无法到达终点
}
};
|