Saturday, July 22nd
Tracking a knight's move on a chessboard is the topic of today's problem
Given a chess board size, an initial position, and number of moves, calculate the probability that a knight will remain on the board after executing the number of moves
Because of the overlapping subproblems, we will approach solving this problem with dynamic programming
First we identify the state variables of the problem. There is the position of the piece on the chessboard, the row and column which is up to the value n. There is also the move we're on. Since we initialize state at move 0, and there are up to and including k moves, the move dimension will be k+1.
This leads to the initialization of a 3-D vector which will store the probability of a knight being at a given square after a given number of moves:
The probability of the knight being at the starting position is 100% so we initialize the the dp vector:
We assume everyone if familiar with the moves of a knight on a chessboard. To help iterating possible knight positions, we create an array holding vectors of knight_turns:
For the bread and butter, the idea is to, for each moves, iterate over all squares in the chess board and find previously occupied squares that can lead to the square under iteration.
We use the knight_turns vector to determine previous squares
Then check if any of the previous squares have been reachable and have a probability assigned. If so, divide that value by 8 (because a knight has 8 possible directions to move).
Finally, to return the total probability, we iterate over all squares and sum the total probability and return it
Interesting application of bottom-up dynamic programming
Thanks to the Editorial for showing a good way to calculate probabilities
Comments
Post a Comment