class Solution {
public static final int[][] dir = new int[][] {{-2, -1}, {-1, -2}, {-2, 1}, {-1, 2}, {1, -2}, {2, -1}, {1, 2}, {2, 1}};
public double knightProbability(int N, int K, int r, int c) {
if (r < 0 || r >= N || c < 0 || c >= N) return 0.0;
double[][] dp = new double[N][N];
dp[r][c] = 1;
double res = 1;
for (int k = 0; k < K; k++) {
double[][] temp = new double[N][N];
res = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
for (int[] d : dir) {
int x = i + d[0];
int y = j + d[1];
if (x >= 0 && x < N && y >= 0 && y < N && dp[x][y] > 0) {
temp[i][j] += 0.125 * dp[x][y];
res += 0.125 * dp[x][y];
}
}
}
}
dp = temp;
}
return res;
}
}