Leetcode 688: Knight Probability in Chessboard

grid47
grid47
Exploring patterns and algorithms
Aug 30, 2024 7 min read

A chessboard where the knight’s possible moves are calculated, with the highest probability glowing softly.
Solution to LeetCode 688: Knight Probability in Chessboard Problem

You are given an n x n chessboard and a knight that starts at a given position (row, column). The knight moves exactly k times and can randomly choose one of eight possible knight moves at each step. The task is to determine the probability that the knight remains on the board after completing all k moves.
Problem
Approach
Steps
Complexity
Input: The input consists of four integers: n (the size of the chessboard), k (the number of moves), row (the starting row), and column (the starting column).
Example: n = 4, k = 3, row = 1, column = 1
Constraints:
• 1 <= n <= 25
• 0 <= k <= 100
• 0 <= row, column <= n - 1
Output: Return a floating point number representing the probability that the knight remains on the chessboard after k moves.
Example: 0.1250
Constraints:
Goal: The goal is to compute the probability that after exactly k moves, the knight stays on the chessboard.
Steps:
• Use a depth-first search (DFS) approach to explore all possible knight moves.
• Memoize results to optimize redundant calculations.
• At each step, check if the knight remains within the bounds of the chessboard.
Goal: The input values are constrained as follows:
Steps:
• n is between 1 and 25.
• k is between 0 and 100.
• row and column are valid indices on the chessboard.
Assumptions:
• The knight will always move randomly and uniformly at each step.
• The chessboard is represented by a 2D grid with indices from 0 to n-1.
Input: Example 1: n = 4, k = 3, row = 1, column = 1
Explanation: The knight has multiple possible moves, but only a subset of these will keep the knight on the board. After exploring all moves, the probability is 0.125.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus