forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
82 lines (66 loc) · 1.82 KB
/
main.cpp
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
80
81
82
/// Source : https://leetcode.com/problems/snakes-and-ladders/description/
/// Author : liuyubobobo
/// Time : 2018-09-22
#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
using namespace std;
/// BFS
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
int n = board.size();
vector<int> b;
int order = 0;
for(int i = n - 1; i >= 0; i --){
if(order)
reverse(board[i].begin(), board[i].end());
for(int j = 0; j < n; j ++){
if(board[i][j] != -1)
board[i][j] --;
b.push_back(board[i][j]);
}
order = 1 - order;
}
assert(b.size() == n * n);
return bfs(b, 0, n * n - 1);
}
private:
int bfs(const vector<int>& b, int s, int t){
vector<bool> visited(b.size(), false);
queue<pair<int, int>> q;
q.push(make_pair(s, 0));
visited[s] = true;
while(!q.empty()){
int pos = q.front().first;
int step = q.front().second;
q.pop();
if(pos == t)
return step;
for(int i = 1; i <= 6 && pos + i < b.size(); i ++){
int next = pos + i;
if(b[next] != -1)
next = b[next];
if(!visited[next]){
visited[next] = true;
q.push(make_pair(next, step + 1));
}
}
}
return -1;
}
};
int main() {
vector<vector<int>> board1 = {
{-1,1,2,-1},
{2,13,15,-1},
{-1,10,-1,-1},
{-1,6,2,8}
};
cout << Solution().snakesAndLadders(board1) << endl;
// 2
return 0;
}