Knight Probability in Chessboard LeetCode solution in Java

1
class Solution {
2
public double knightProbability(int n, int k, int row, int column) {
3
double[][] curr = new double[n][n];
4
double[][] next = new double[n][n];
5

6
curr[row][column] = 1;
7

8
int[][] dir = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};
9
for (int p = 1; p <= k; p++) {
10
for (int i = 0; i < n; i++) {
11
for (int j = 0; j < n; j++) {
12
if (curr[i][j] != 0) {
13

14
for (int d = 0; d < 8; d++) {
15
int ni = i + dir[d][0];
16
int nj = j + dir[d][1];
17

18
if (ni < 0 || nj < 0 || ni >= n || nj >= n) {
19
continue;
20
}
21

22
next[ni][nj] += curr[i][j] / 8.0;
23
}
24
}
25
}
26
}
27

28
curr = next;
29
next = new double[n][n];
30
}
31

32
double sum = 0.0;
33

34
for (int i = 0; i < n; i++) {
35
for (int j = 0; j < n; j++) {
36
sum += curr[i][j];
37
}
38
}
39

40
return sum;
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0