[InterviewBit] Snake Ladder Problem!

Snake Ladder Problem!

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int Solution::snakeLadder(vector<vector<int>> &A, vector<vector<int>> &B) {
vector<int> vis(101, -1);
queue<int> q;
q.push(1);
vis[0] = vis[1] = 0;
unordered_map<int, int> mp;
for(auto vec : A) mp[vec[0]] = vec[1];
for(auto vec : B) mp[vec[0]] = vec[1];
while(q.size()) {
auto u = q.front(); q.pop();
for(int i = 1; i <= 6; i++) {
if(u + i > 100 or vis[u + i] != -1) continue;
vis[u + i] = vis[u] + 1;
if(mp.count(u + i)) {
if(vis[mp[u + i]] == -1) {
q.push(mp[u + i]);
vis[mp[u + i]] = vis[u] + 1;
}
} else q.push(u + i);
}
}

return vis[100];
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/01/PS/interviewbit/snake-ladder-problem/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.