Advertisement
1988coder

688. Knight Probability in Chessboard

Feb 7th, 2019
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/knight-probability-in-chessboard/
  2.  
  3. /**
  4.  * Dynamic Programming
  5.  *
  6.  * DP[i][j] = Probability of knight being moved here after K moves.
  7.  *
  8.  * Time Complexity: O(8 * K * N^2)
  9.  *
  10.  * Space Complexity: O(N^2)
  11.  *
  12.  * N = chess board size. K = Number of moves.
  13.  */
  14. class Solution {
  15.     public double knightProbability(int N, int K, int r, int c) throws IllegalArgumentException {
  16.         if (N <= 0 || K < 0 || r < 0 || c < 0) {
  17.             throw new IllegalArgumentException("Invalid input");
  18.         }
  19.         if (r >= N || c >= N) {
  20.             return 0.0;
  21.         }
  22.         if (K == 0) {
  23.             return 1;
  24.         }
  25.  
  26.         int[][] dirs = new int[][] { { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 }, { 1, -2 }, { 1, 2 }, { -1, -2 },
  27.                 { -1, 2 } };
  28.  
  29.         double[][] dp = new double[N][N];
  30.         dp[r][c] = 1.0;
  31.  
  32.         while (K > 0) {
  33.             double[][] dpNew = new double[N][N];
  34.             for (int i = 0; i < N; i++) {
  35.                 for (int j = 0; j < N; j++) {
  36.                     if (dp[i][j] > 0) {
  37.                         for (int[] d : dirs) {
  38.                             int row = i + d[0];
  39.                             int col = j + d[1];
  40.                             if (row < 0 || col < 0 || row >= N || col >= N) {
  41.                                 continue;
  42.                             }
  43.                             dpNew[row][col] += dp[i][j] / 8.0;
  44.                         }
  45.                     }
  46.                 }
  47.             }
  48.             dp = dpNew;
  49.             K--;
  50.         }
  51.  
  52.         double result = 0.0;
  53.         for (int i = 0; i < N; i++) {
  54.             for (int j = 0; j < N; j++) {
  55.                 result += dp[i][j];
  56.             }
  57.         }
  58.         return result;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement