Given a snake and ladder board of order 5x6, find the minimum number of dice throws required to reach the destination or last cell (30th cell) from source (1st cell) . - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Monday 29 June 2020

Given a snake and ladder board of order 5x6, find the minimum number of dice throws required to reach the destination or last cell (30th cell) from source (1st cell) .

Given a snake and ladder board of order 5x6, find the minimum number of dice throws required to reach the destination or last cell (30th cell) from source (1st cell)


Given a snake and ladder board of order 5x6, find the minimum number of dice throws required to reach the destination or last cell (30th cell) from source (1st cell). 

For Input:
2
2
20 11 21 3
2
12 18 3 19
Your Output is:
5
3


#include <bits/stdc++.h>

using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, x, y;
        cin >> n;
        unordered_map < int, int > mp;

        for (int i = 0; i < n; ++i) {
            cin >> x >> y;
            mp[x] = y;
        }
        queue < pair < int, int > > q;
        int a[31];
        memset(a, 0, sizeof(a));
        a[1] = 0;
        q.push(make_pair(1, 0));
        int res = 0, f = 0;
        while (!q.empty() && a[30] == 0) {
            auto p = q.front();
            x = p.first, y = p.second;
            ++y;
            q.pop();

            for (int i = 1; i <= 6; ++i) {
                if (a[i + x] == 0) {
                    if (mp.find(i + x) == mp.end()) {
                        q.push(make_pair(i + x, y));
                        a[i + x] = 1;
                    } else {
                        if (a[mp[i + x]] == 0) {
                            q.push(make_pair(mp[i + x], y));
                            a[mp[i + x]] = 1;
                        }

                    }
                }

                if (a[30] == 1) {
                    f = 1;
                    res = y;
                    break;

                }

            }

            if (f || a[30] == 1) break;

        }

        cout << res << endl;
    }
    return 0;
}