제약 사항
- 1 <= n <= 25
- 0 <= k <= 100
💡 즉, k가 최대 100이므로 완전탐색은 불가능하고, DP를 활용해야 한다.
몇 번 이동
했는지에 따라 확률 값이 달라질 수 있다.dp[y][x][depth] = depth 번의 이동동안 y, x에 도달할 수 있는 확률
O(n^2*k)
로 시간 복잡도를 줄일 수 있다.int dy[8] = {2,1,-1,-2,-2,-1,1,2};
int dx[8] = {1,2,2,1,-1,-2,-2,-1};
double dfs(int y, int x, int n, int k, int depth, double total) {
if(depth == k){
dp[y][x][depth] = 1.0 / total;
return 1.0 / total;
}
if(dp[y][x][depth] != -1){
return dp[y][x][depth];
}
double temp = 0;
for(int i= 0 ; i<8; i++){
int py = y + dy[i];
int px = x + dx[i];
if(py < 0 || px < 0 || py >= n || px >= n){
continue;
}
temp += dfs(py, px, n, k, depth+1, total);
}
dp[y][x][depth] = temp;
return temp;
}
class Solution {
public:
int dy[8] = {2,1,-1,-2,-2,-1,1,2};
int dx[8] = {1,2,2,1,-1,-2,-2,-1};
double dp[26][26][101];
double dfs(int y, int x, int n, int k, int depth, double total) {
if(depth == k){
dp[y][x][depth] = 1.0 / total;
return 1.0 / total;
}
if(dp[y][x][depth] != -1){
return dp[y][x][depth];
}
double temp = 0;
for(int i= 0 ; i<8; i++){
int py = y + dy[i];
int px = x + dx[i];
if(py < 0 || px <0 || py >= n || px >= n){
continue;
}
temp += dfs(py,px,n,k,depth+1,total);
}
dp[y][x][depth] = temp;
return temp;
}
double knightProbability(int n, int k, int row, int column) {
for(int i= 0 ; i < 26; i++){
for(int j= 0 ; j<26; j++){
for(int k = 0 ; k<101; k++){
dp[i][j][k] = -1;
}
}
}
return dfs(row, column, n, k ,0, pow(8,k));
}
};