Data Structure & Algorithms
  • 🖌️Unlocking the Power of Algorithms with C#
  • Data Structure
    • Data Structure
    • Big O
    • Array
    • Linked Lists
    • Stacks
    • Queues
    • Hash Tables
    • Trees
    • Graphs
    • Heap Sort
    • ParkingLot Algorithm
    • LRU cache
    • Priority Queue
  • Algorithms
    • Algorithm
    • Recursion
    • Sorting
    • Searching
    • Dynamic Programming
  • Problems
    • Array
      • Two Sum
      • Two Sum II - Input Array Is Sorted
      • Contains Duplicate
      • Maximum Subarray
      • House Robber
      • Move Zeroes
      • Rotate Array
      • Plus One
      • Find number of subarrays with even length
      • Find number of subarrays with even sum
      • Find Missing Element
      • Reduce Array Size to The Half
      • Remove Duplicates
      • Merge Sorted Arrays
      • Arrays Intersection
      • 3Sum
      • Trapping Rain Water
      • Maximum sum of a subarray
      • Longest Subarray
      • Subarray Sum Equals K
      • Container With Most Water
      • Missing Number
      • Roman to Integer
      • First Missing Positive
      • Unique Integers That Sum Up To 0
      • Integer to Roman
      • Flatten
    • String
      • Check if two strings are permutation of each other
      • String Compression
      • Palindrome Permutation
      • Determine if a string has all Unique Characters
      • One Away
      • Longest Substring Without Repeating Characters
      • Valid Palindrome
      • Valid Palindrome II
      • Backspace String Compare
      • First Unique Character in a String
      • Is Subsequence
      • URLify a given string
      • String has same characters at same position
      • Number of Ways to Split a String
      • Check whether two Strings are anagram of each other
      • Print last `n` lines of a big file or big string.
      • Multiply Strings
    • Matrix
      • Search a 2D Matrix
      • Search a 2D Matrix II
      • Rotate Matrix
      • Spiral Matrix
      • Set Matrix Zeroes
    • Bit Manipulation
      • Sum of Two Integers
      • Reverse Number
      • Reverse Number II
      • Binary Bits Count
      • Binary Bits Count II
    • Stack
      • Valid Parentheses
      • Balance or not expression
      • Decode String
    • Tree
      • Binary Tree Inorder Traversal
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Return All Root-To-Leaf Paths
      • Binary Tree Height-Balanced
      • Valid Binary Search Tree
      • Binary Tree Sum of all left leaves.
    • Linked List
      • Linked List Delete Middle Node
      • Merge Sorted Linked List
      • Reverse Linked List
      • Remove Duplicates from Sorted List
      • Remove Duplicates from Unsorted List
      • Linked List Cycle
    • Graph
      • The Number Of Islands
      • Number of Closed Islands
      • Max Area of Island
      • Rotting Oranges
      • Number of Provinces
      • Course Schedule
      • Surrounded Regions
      • Snakes and Ladders
      • Widest Path Without Trees
      • Knight Probability in Chessboard
      • Possible moves of knight
      • Check Knight Tour Configuration
      • Steps by Knight
      • Network Delay Time
    • Greedy
      • Best Time to Buy and Sell Stock
      • Best Time to Buy and Sell Stock II
      • Smallest Subset Array
      • Jump Game
    • Backtracking
      • Towers of Hanoi
      • Subsets
      • Combination Sum
      • Sudoku Solver
      • Word Search
    • Heap
      • Kth Largest Element in an Array
      • Top K Frequent Elements
    • Sorting
      • Order Colors String
    • Recursion
      • Number To Text
      • Divide Number
Powered by GitBook
On this page
  1. Problems
  2. Graph

Knight Probability in Chessboard

PreviousWidest Path Without TreesNextPossible moves of knight

Last updated 1 year ago

On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).

A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.

Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.

The knight continues moving until it has made exactly k moves or has moved off the chessboard.

Return the probability that the knight remains on the board after it has stopped moving.

Example 1:

Input: n = 3, k = 2, row = 0, column = 0
Output: 0.06250
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.

Example 2:

Input: n = 1, k = 0, row = 0, column = 0
Output: 1.00000

Constraints:

  • 1 <= n <= 25

  • 0 <= k <= 100

  • 0 <= row, column <= n - 1

Solutions

This problem can be solved using dynamic programming. The idea is to keep track of the probability of reaching each cell after a certain number of moves. We start with the initial cell and for each move, we distribute its probability to all the reachable cells. After all moves, we sum up the probabilities of all cells to get the final result.

Approach -BFS

The problem can also be solved using Breadth-First Search (BFS). The idea is to start from the initial cell and for each cell, we calculate the probability of reaching it from all its reachable cells. We continue this process until we have made all the moves. The final result is the sum of the probabilities of all cells after k moves.


public class Solution
{
    //cache response
    private double?[,,] memo;
    // There is only 8 possible way that a Knight can move within the chessboard. 
    private (int, int)[] directions = [(-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1)];
    public double KnightProbability(int n, int k, int row, int column)
    {
        memo = new double?[n, n, k + 1];


        return KnightProbabilityHelper(n, k, row, column);
    }

    private double KnightProbabilityHelper(int n, int k, int row, int column)
    {

        //check initial position of Knight is valid
        if (row < 0 || row >= n || column < 0 || column >= n)
        {
            return 0.0;
        }
        //check move is valid
        if (k == 0)
        {
            return 1.00;
        }
        //check same value already calculated.
        if (memo[row, column, k].HasValue)
        {
            return memo[row, column, k].Value;
        }

        double res = 0.0;
        foreach (var (x, y) in directions)
        {
            // move next step
            int newRow = row + x;
            int newColumn = column + y;
            if (newRow >= 0 && newRow < n && newColumn >= 0 && newColumn < n)
            {
                res += KnightProbabilityHelper(n, k - 1, newRow, newColumn) / directions.Length;
            }
        }
        //store value into cache store
        memo[row, column, k]=res;
        return res;
    }
}

The time and space complexity of the given algorithm is as follows:

  • Time Complexity: The time complexity of this algorithm is O(n^2 * k). Here, n is the size of the chessboard and k is the number of moves. This is because for each move, we are exploring 8 possible moves for each cell in the n x n chessboard.

  • Space Complexity: The space complexity of this algorithm is also O(n^2 * k). This is due to the 3D memoization array that we are using to store the computed probabilities for each cell for a given number of moves. The size of this 3D array is n x n x k.