Simple BFS || C++ || Constant time


#1

`int Solution::snakeLadder(vector<vector > &A, vector<vector > &B) {
int start = 1, dest = 100, infi = 2e9;
unordered_map<int, int> ladders, snakes;
vector dist(101, infi);
vector dice = {1, 2, 3, 4, 5, 6};
queue q;

for(auto l : A) ladders[l[0]] = l[1];
for(auto s : B) snakes[s[0]] = s[1];

dist[start] = 0;
q.push(start);

while(!q.empty()) {
    auto currPos = q.front(); q.pop(); 
    for(auto roll : dice) {
        int newPos = roll + currPos;
        if(newPos <= dest) {
            if(ladders.find(newPos) != ladders.end()) newPos = ladders[newPos];
            else if(snakes.find(newPos) != snakes.end()) newPos = snakes[newPos];
            
            if(dist[newPos] == infi) {
                dist[newPos] = dist[currPos] + 1;
                q.push(newPos);
            }
        }
    }
}

auto ans = dist[dest];
if(ans == infi) ans = -1;

return ans;

}
`