problem:https://leetcode.com/problems/snakes-and-ladders/
这道题需要换算位置和数字之间的关系,虽然并不难但是很繁琐。
因为遇到了梯子/蛇一定要滑过去,所以我们可以当作把这一位置作为跳板直接到达了梯子末端,就好像没有来过这一位置一样。
class Solution { public: int m, n; int getNumber(int pos) { int i = pos / n; int j = pos % n; i = m - 1 - i; int num = n * i; if (i % 2) { num += n - j; } else { num += j + 1; } return num; } int getPos(int number) { number -= 1; int i = number / n; int j = number % n; int pos = 0; if (i % 2) { pos += n - j - 1; } else { pos += j; } i = m - 1 - i; pos += n * i; return pos; } int snakesAndLadders(vector<vector<int>>& board) { m = board.size(); if (!m) return 0; n = board[0].size(); queue<int> q; q.push((m - 1) * n); vector<int> dist(m * n, INT_MAX); vector<bool> visit(m * n, false); dist[(m - 1) * n] = 0; visit[(m - 1) * n] = true; while(!q.empty()) { int cur = q.front(); int i = cur / n; int j = cur % n; q.pop(); int num = getNumber(cur); for (int k = 1; k <= 6; k++) { int next = num + k; int pos = getPos(next); // check snake or ladder if (pos >= 0 && pos < m * n) { int newNumber = board[pos / n][pos % n]; if (newNumber != -1) { next = newNumber; pos = getPos(next); } } if (pos >= 0 && pos < m * n) { if (!visit[pos]) { visit[pos] = true; dist[pos] = dist[cur] + 1; q.push(pos); } } } } if (dist[getPos(m * n)] == INT_MAX) return -1; return dist[getPos(m * n)]; } };