1. DFS with Visited Depth Tracking
Intuition
Explore all possible sequences of die rolls (1 to 6) recursively using Depth-First Search. Maintain a minRolls array where minRolls[sq] stores the minimum rolls found so far to reach square sq. If current rolls >= minRolls[sq], prune the branch. Return minRolls[N^2].
Algorithm
- Create helper
getPos(sq, n)to map square number to(row, col). - Initialize
minRollsarray of size n2 + 1 with infinity, setminRolls[1] = 0. - Define
dfs(curr, rolls): - If
rolls >= minRolls[curr], return. -
minRolls[curr] = rolls. - If
curr == n * n, return. - For die = 1 to 6:
-
next = curr + die - If
next > n * n, break. -
destination = board[r][c] != -1 ? board[r][c] : next -
dfs(destination, rolls + 1) - Run
dfs(1, 0). - Return
minRolls[n*n] == infinity ? -1 : minRolls[n*n].
#include <iostream>#include <vector>#include <algorithm>#include <climits> std::pair<int, int> getCoordinates(int sq, int n) { int r = n - 1 - (sq - 1) / n; int c = (sq - 1) % n; if (((sq - 1) / n) % 2 == 1) { c = n - 1 - c; } return {r, c};} void dfs(int curr, int rolls, int n, const std::vector<std::vector<int>>& board, std::vector<int>& minRolls) { if (rolls >= minRolls[curr]) return; minRolls[curr] = rolls; if (curr == n * n) return; for (int die = 1; die <= 6 && curr + die <= n * n; ++die) { int next = curr + die; auto [r, c] = getCoordinates(next, n); int dest = (board[r][c] != -1) ? board[r][c] : next; dfs(dest, rolls + 1, n, board, minRolls); }} int snakesAndLaddersDFS(std::vector<std::vector<int>>& board) { int n = board.size(); std::vector<int> minRolls(n * n + 1, INT_MAX); dfs(1, 0, n, board, minRolls); return minRolls[n * n] == INT_MAX ? -1 : minRolls[n * n];} int main() { std::vector<std::vector<int>> board = {{-1,-1},{-1,3}}; std::cout << "Snakes and Ladders (DFS): " << snakesAndLaddersDFS(board) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(6^(N^2)) worst case without aggressive pruning because each square branches into up to 6 choices. - Space complexity:
O(N^2) for the recursion call stack and distance array.