From f61396cad85734b4783a75e689c98aa04ad8c72a Mon Sep 17 00:00:00 2001 From: atulyadav745 <106299466+atulyadav745@users.noreply.github.com> Date: Thu, 14 Jul 2022 20:44:16 +0530 Subject: [PATCH] snake_ladder --- c/snake_and_ladder.cpp | 72 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 c/snake_and_ladder.cpp diff --git a/c/snake_and_ladder.cpp b/c/snake_and_ladder.cpp new file mode 100644 index 0000000..ee39fdc --- /dev/null +++ b/c/snake_and_ladder.cpp @@ -0,0 +1,72 @@ +// snake and ladder problem +#include "bits/stdc++.h" + +using namespace std; +int32_t main() +{ + int ladders, snakes; + cin >> ladders; + map lad; + map snak; + for (int i = 0; i < ladders; i++) + { + int u, v; + cin >> u >> v; + lad[u] = v; + } + cin >> snakes; + for (int i = 0; i < snakes; i++) + { + int u, v; + cin >> u >> v; + snak[u] = v; + } + int moves = 0; + queue q; + q.push(1); + bool found = false; + vector vis(101, 0); + vis[1] = true; + while (!q.empty() and !found) + { + int sz = q.size(); + while (sz--) + { + int t = q.front(); + q.pop(); + for (int die = 1; die <= 6; die++) + { + if (t + die == 100) + found = true; + if (t + die <= 100 and lad[t + die] and !vis[lad[t + die]]) + { + vis[lad[t + die]] = true; + if (lad[t + die] == 100) + { + found = true; + } + q.push(lad[t + die]); + } + else if (t + die <= 100 and snak[t + die] and !vis[snak[t + die]]) + { + vis[snak[t + die]] = true; + if (snak[t + die] == 100) + found = true; + q.push(snak[t + die]); + } + else if (t + die <= 100 and !vis[t + die] and !snak[t + die] and !lad[t + die]) + { + vis[t + die] = true; + q.push(t + die); + } + } + } + moves++; + } + if (found) + cout << moves; + else + { + cout << -1; + } +} \ No newline at end of file