688. Knight Probability in Chessboard

 1 class Solution {
 2     public double knightProbability(int N, int K, int r, int c) {
 3         if(K == 0) return 1;
 4         double[][][] dp = new double[K+1][N][N];
 5         int[][] move = {{1,2}, {2,1}, {-1,-2}, {-2,-1}, {-1,2}, {-2,1},{1,-2},{2,-1}};
 6         dp[0][r][c] = 1;
 7         for(int i = 1; i <= K; i++){
 8             for(int row = 0; row < N; row++){
 9                 for(int col = 0; col < N; col++){
10                     if(dp[i-1][row][col] != 0){
11                         for(int k = 0; k < 8; k++){
12                             // System.out.println((col + move[k][1]) >=0);
13                             int x = row + move[k][0];
14                             int y = col + move[k][1];
15                             if(x >=0 && x < N && y >=0 && y < N){
16                               dp[i][x][y] += dp[i-1][row][col]/8; 
17                               
18                             }
19                         }
20                     }
21                 }
22             }
23         }
24         double count = 0;
25         for(int i = 0; i < N; i++){
26             for(int j = 0; j < N; j++){
27                 count += dp[K][i][j];
28             }
29         }
30         return count;
31         
32     }
33 }

 

posted @ 2018-10-28 01:54  jasoncool1  阅读(152)  评论(0编辑  收藏  举报