Sponsored
Sponsored
The Snakes and Ladders board can be seen as a graph where each square is a node, and an edge exists between node i and node j if you can move from square i to square j with a dice roll. Use BFS to efficiently explore this graph, ensuring each move accounts for ladders and snakes.
Time Complexity: O(n^2), where n is the board dimension, as each square is processed once.
Space Complexity: O(n^2), for storing the queue and visited status of squares.
1#include <vector>
2#include <queue>
3#include <unordered_map>
4
5using namespace std;
6
7class Solution {
8public:
9 int snakesAndLadders(vector<vector<int>>& board) {
10 int n = board.size();
11 vector<int> flattenBoard(n * n + 1, -1);
12 int idx = 1;
13 bool leftToRight = true;
14 for (int i = n - 1; i >= 0; --i) {
15 if (leftToRight) {
16 for (int j = 0; j < n; ++j) {
17 flattenBoard[idx++] = board[i][j];
18 }
19 } else {
20 for (int j = n - 1; j >= 0; --j) {
21 flattenBoard[idx++] = board[i][j];
22 }
23 }
24 leftToRight = !leftToRight;
25 }
26
27 queue<pair<int, int>> q;
28 vector<bool> visited(n * n + 1, false);
29 q.push({1, 0});
30 visited[1] = true;
31
32 while (!q.empty()) {
33 auto [pos, moves] = q.front();
34 q.pop();
35 if (pos == n * n) return moves;
36
37 for (int i = 1; i <= 6; ++i) {
38 int nextPos = pos + i;
39 if (nextPos <= n * n) {
40 if (flattenBoard[nextPos] != -1) {
41 nextPos = flattenBoard[nextPos];
42 }
43 if (!visited[nextPos]) {
44 visited[nextPos] = true;
45 q.push({nextPos, moves + 1});
46 }
47 }
48 }
49 }
50
51 return -1;
52 }
53};
The C++ solution uses the same BFS approach as the previous one. It flattens the board and uses a queue to process each position, incrementing moves and checking for direct paths via snakes or ladders.
Dijkstra's Algorithm typically finds shortest paths in weighted graphs. Adapting it for an unweighted snakes and ladders board can ensure the fewest moves to reach the final square by evaluating and using priority. Each move is computed implicitly based on its dice-distance weight.
Time Complexity: O(n^2 log(n^2)), given heap operations for prioritized traversal.
Space Complexity: O(n^2) for heap management.
1
JavaScript's solution leverages a priority queue interfaced via a minimum heap, efficiently matching Dijkstra's logic style for shortest path discernment.