Snakes and Ladders
LeetCode 909 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
BFS over squares; zig-zag coordinate conversion.
ನಾನು Snakes and Ladders (LeetCode 909) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — State-Space BFS ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Each square is a node; a dice roll moves 1–6 squares, after which a snake or ladder may teleport you. The minimum number of rolls is a BFS. The only fiddly part is converting a square number to its zig-zag board position.
Approach
- 1
get_row_col: row from the bottom, column reversed on alternate rows.
- 2
BFS from square 1.
- 3
For each roll, follow a snake/ladder if present.
- 4
Reaching n² returns steps + 1.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
BFSPythonO(n²) time
class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
#observations
#we are going step by step - need to return step -bfs
#for odd rows it starts from
#so to calculate rows/cols we need to substract from n-1
def get_row_col_from_pos(pos):
n = len(board)
row = (pos-1)//n
col = (pos-1)%n
if row%2!=0:
col = n-1-col
row = n-1-row
return (row,col)
n = len(board)
q = deque([(1,0)])
visited = set()
visited.add(1)
while q:
square,steps=q.popleft()
for i in range(1,7):
next_pos = square+i
row,col = get_row_col_from_pos(next_pos) #get next from postion from cur_pos+ btwn 1 to 6 range
if board[row][col]!=-1:
next_pos=board[row][col] #snake or ladder
if next_pos==n*n: #check this after getting next_pos since next position either can be a snake/ladder
return steps+1
if next_pos not in visited:
visited.add(next_pos)
q.append((next_pos,steps+1))
return -1
Snakes and Ladders — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Snakes and Ladders ಹಿಂದಿನ intuition ಏನು?
Each square is a node; a dice roll moves 1–6 squares, after which a snake or ladder may teleport you. The minimum number of rolls is a BFS. The only fiddly part is converting a square number to its zig-zag board position.
Snakes and Ladders (LeetCode 909) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. get_row_col: row from the bottom, column reversed on alternate rows. 2. BFS from square 1. 3. For each roll, follow a snake/ladder if present. 4. Reaching n² returns steps + 1.
Snakes and Ladders ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n²). Space: O(n²). (Accepted approach: BFS.)
Snakes and Ladders ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Only follow one snake/ladder per move (no chaining).