1. Description
Given an N*N chessboard, a knight starts at the row and c column and makes k moves.
Return the probability that the knight remains on the board.
2. Solution
Use dynamic programming.
For every step, calculate the number of ways to reach every gird.
After K steps, we can get the number of ways to reach (r,c).
The number divide pow(8,k) is the final answer.
这道题说明,走出格子有两种思路。
一个是从起点出发,走k步,统计有多少种方法可以走出格子。或者每个格子的和加起来就是留在格子上的方法。
一个是从每个点出发,走k步,统计有多少种方法可以走到出发点。
走出格子的方法+不走出格子的方法!= pow(4或者8,k)。
3. Code
double knightProbability(int N, int K, int r, int c) {
vector<vector<double> > p(N,vector<double>(N,1));
for(int k=0;k<K;k++){
vector<vector<double> > p2(N,vector<double>(N,0));
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
double cnt = 0;
for(int a=0;a<8;a++){
int x = i + xx[a];
int y = j + yy[a];
if(x>=0&&x<N&&y>=0&&y<N)
cnt+=p[x][y];
}
p2[i][j]=cnt;
}
}
p=p2;
}
return double(p[r][c]*1.0/pow(8,K));
}
int xx[8]={-2,-2,-1,-1,1,1,2,2};
int yy[8]={1,-1,2,-2,2,-2,1,-1};