题目:力扣
思路:官方思路
class Solution {
fun knightProbability(N: Int, K: Int, r: Int, c: Int): Double {
var currentMatrix = Array(N) { DoubleArray(N) {0.0} }
var nextMatrix = Array(N) { DoubleArray(N) {0.0} }
currentMatrix[r][c] = 1.0
var possibleMoveArr = arrayOf(
arrayOf(-1, 2),
arrayOf(1, 2),
arrayOf(2, 1),
arrayOf(2, -1),
arrayOf(1, -2),
arrayOf(-1, -2),
arrayOf(-2, -1),
arrayOf(-2, 1)
)
var result = 0.0
for (k in 1..K) {
for (i in 0 until N) {
for (j in 0 until N) {
if (currentMatrix[i][j] != 0.0) {
var nextI = 0
var nextJ = 0
for (move in 0 until 8) {
nextI = i + possibleMoveArr[move][0]
nextJ = j + possibleMoveArr[move][1]
if (isMoveValid(nextI, nextJ, N)) {
nextMatrix[nextI][nextJ] += currentMatrix[i][j] / 8.0
}
}
}
}
}
currentMatrix = nextMatrix
nextMatrix = Array(N) { DoubleArray(N) {0.0} }
}
for (i in 0 until N) {
for (j in 0 until N) {
result += currentMatrix[i][j]
}
}
return result
}
fun isMoveValid(nextI: Int, nextJ: Int, n: Int): Boolean {
if (nextI >= 0 && nextJ >= 0 && nextI < n && nextJ < n) {
return true
} else {
return false
}
}
}
class Solution {
static int[][] dirs = {{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}};
public double knightProbability(int n, int k, int row, int column) {
double[][][] dp = new double[k + 1][n][n];
for (int step = 0; step <= k; step++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (step == 0) {
dp[step][i][j] = 1;
} else {
for (int[] dir : dirs) {
int ni = i + dir[0], nj = j + dir[1];
if (ni >= 0 && ni < n && nj >= 0 && nj < n) {
dp[step][i][j] += dp[step - 1][ni][nj] / 8;
}
}
}
}
}
}
return dp[k][row][column];
}
}