Java implementation LeetCode 688 "horses" probability on the board (DFS + memory search)

688. "horse" probability on the board

Given a NxN chess board, chessboard row and column numbers are zero-based. I.e., the upper left corner of the grid as (0, 0), the lower right corner is referred to as a (N-1, N-1).

An existing "horse" (also translated as "Knight") located at (r, c), K times and intend to move.

, The chess "Ma" at each step to move below the horizontal or vertical direction in FIG. 2 lattice, a lattice is then moved again to the direction perpendicular thereto, a total of eight optional positions.

Here Insert Picture Description

Now "Ma" every step from an optional position (including the external board) independently move randomly selects one, or K times until the skip is moved outside the board.

After the completion of the movement seeking, "horse" remains on the board of probability.

Example:

Input: 3, 2, 0, 0
Output: 0.0625
interpretation:
data input successively is N, K, r, c
during the first step, and only on a two Act "Ma" may be left on the board (jump ( 1,2) or (2,1)). For more than two cases each were in step 2 and walking only two kinds Act "horse" remained on the board.
Therefore, the "horse" after the probability is still on the board of 0.0625.

note:

N ranges [. 1, 25]
K is in the range [0, 100]
at the beginning, "Ma" is always located on the board

class Solution {
    int[][] move = { { 1, 2 }, { 1, -2 }, { 2, 1 }, { 2, -1 }, { -1, 2 }, { -1, -2 }, { -2, 1 }, { -2, -1 } };
	double[][][] dp;

	public double knightProbability(int N, int K, int r, int c) {
		dp = new double[N][N][K + 1];
		if (K == 0)
			return 1;
		return dfs(N, K, r, c);
	}

	private double dfs(int N, int K, int r, int c) {
		if (dp[r][c][K] != 0)
			return dp[r][c][K];
		double res = 0;
		for (int i = 0; i < 8; i++) {
			int r1 = r + move[i][0];
			int c1 = c + move[i][1];
			if (r1 >= 0 && r1 < N && c1 >= 0 && c1 < N) {
				res += (K == 1 ? 1 : dfs(N, K - 1, r1, c1));
			}
		}
		return dp[r][c][K] = res / 8;
	}
}
Released 1738 original articles · won praise 30000 + · views 3.66 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105329006