Skip to content

Commit c478194

Browse files
Add Cpp solution to problem 909 (snakes and ladders)
1 parent 822c53a commit c478194

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

cpp/0909-snakes-and-ladders.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class Solution {
2+
public:
3+
// Function to get the row and column index of a position on the board
4+
std::pair<int, int> get_indexes_of(int pos, std::vector<std::vector<int>>& grid)
5+
{
6+
int grid_w = grid.front().size();
7+
int grid_h = grid.size();
8+
int r = (pos - 1) / grid_w;
9+
int c = (pos - 1) % grid_w;
10+
// Adjust column index for alternating rows
11+
c = r % 2 == 0 ? c : grid_w - (c + 1);
12+
// Adjust row index to start from the bottom of the grid
13+
r = grid_h - (r + 1);
14+
return std::make_pair(r, c);
15+
}
16+
17+
// Function to find the minimum number of moves to reach the last cell in Snakes and Ladders
18+
// using BFS (Breadth-First Search).
19+
// BFS lets us find the shortest path in an unweighted graph.
20+
int snakesAndLadders(std::vector<std::vector<int>>& board)
21+
{
22+
int board_h = board.size();
23+
int board_w = board.front().size();
24+
std::vector<bool> visited((board_h * board_w) + 1, false);
25+
std::vector<int> dist((board_h * board_w) + 1, -1);
26+
std::deque<int> q;
27+
q.push_back(1);
28+
visited[1] = true;
29+
dist[1] = 0;
30+
31+
while (!q.empty())
32+
{
33+
int curr_pos = q.front();
34+
q.pop_front();
35+
36+
// If we reach the last cell, return the distance
37+
if (curr_pos == board_h * board_w) return dist[board_h * board_w];
38+
39+
// Check the next 6 possible moves
40+
for (size_t i = 1; i <= 6; ++i)
41+
{
42+
int next_pos = curr_pos + i;
43+
if (next_pos > board_h * board_w) continue;
44+
45+
std::pair<int, int> next_idx = get_indexes_of(next_pos, board);
46+
// If there's a snake or ladder, move to the destination cell
47+
if (board[next_idx.first][next_idx.second] != -1)
48+
next_pos = board[next_idx.first][next_idx.second];
49+
50+
// If the next position is not visited, mark it and update the distance
51+
if (!visited[next_pos])
52+
{
53+
visited[next_pos] = true;
54+
q.push_back(next_pos);
55+
// dist[next_pos] indicates the number of minimum moves to reach the next position
56+
dist[next_pos] = dist[curr_pos] + 1;
57+
}
58+
}
59+
}
60+
// If we can't reach the last cell, return -1
61+
return -1;
62+
}
63+
};

0 commit comments

Comments
 (0)