vector<vector<int>> grid(R, vector<int>(C, 0)); int last = 0; for (int r = R - 1; r >= 0; r--) { int c = ((-r + R) & 1) ? 0 : C - 1; for (; c >= 0 && c < C; last++) { grid[r][c] = last + 1; heap[last + 1] = {r, c}; if ((-r + R) & 1) c++; else c--; } }
int target = R * C; q[++tt] = {{R - 1, 0}, 0}; board[R - 1][0] = 0x3f3f3f3f; for (; tt >= hh; hh++) { int r = q[hh].first.first, c = q[hh].first.second; int x = grid[r][c]; int cnt = q[hh].second; ++cnt; for (int i = 1; i <= 6; i++) { int nex = x + i; int ner = heap[nex].first, nec = heap[nex].second; //cout << "ner: " << ner << " nec: " << nec << " nex: " << nex << " cnt: " << cnt << endl; if (nex == target || board[ner][nec] == target) { return cnt; } if (nex > target || board[ner][nec] == 0x3f3f3f3f) continue; // determine teleport beacon if (board[ner][nec] > 0) { q[++tt] = {heap[board[ner][nec]], cnt}; } else { q[++tt] = {{ner, nec}, cnt}; } board[ner][nec] = 0x3f3f3f3f; } } return-1; } };
intsnakesAndLadders(vector<vector<int>>& board){ int n = board.size(), m = board[0].size(); id = vector<vector<int>>(n, vector<int>(m)); cor = vector<PII>(n * m + 1); for (int i = n - 1, k = 1, s = 0; i >= 0; i --, s ++ ) { if (s % 2 == 0) { for (int j = 0; j < m; j ++, k ++ ) { id[i][j] = k; cor[k] = {i, j}; } } else { for (int j = m - 1; j >= 0; j --, k ++ ) { id[i][j] = k; cor[k] = {i, j}; } } }
queue<PII> q; vector<vector<int>> dist(n, vector<int>(m, 1e9)); q.push({n - 1, 0}); dist[n - 1][0] = 0; while (q.size()) { auto t = q.front(); q.pop();
int k = id[t.x][t.y]; if (k == n * m) return dist[t.x][t.y]; for (int i = k + 1; i <= k + 6 && i <= n * m; i ++ ) { int x = cor[i].x, y = cor[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 r = board[x][y]; x = cor[r].x, y = cor[r].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; } };