leetcode 688. Knight Probability in Chessboard

題目688. Knight Probability in Chessboard
等級: hard

思路

使用動態規劃,對於N*N的方格,外圍擴展兩層,變成(N+4)(N + 4), 對於外圍的兩層, df[][][] = 0; df[i][j][k] = sum(df[i + di][j + dj][k - 1])/8.0

實現

# include <iostream>
# include <vector>
# include <cstring>

using namespace std;

const int N_MAX = 26, K_MAX = 102;
const int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
const int dy[8] = {-1, -2, -2, -1, 1, 2, 2, 1};

double df[N_MAX + 4][N_MAX + 4][K_MAX];

class Solution {
public:

  double knightProbability(int N, int K, int r, int c) {
    if(K == 0) return 1;

    for(int i = 0; i <= N + 4; i++)
        for(int j = 0; j <= N + 4; j++)
            for(int t = 0; t <= K; t++)
                df[i][j][t] = 0;

    for(int i = 2; i <= N + 1; i++)
      for(int j = 2; j <= N + 1; j++)
        df[i][j][0] = 1;

    for(int i = 1; i <= K; i++) {
      for(int x = 2; x <= N + 1; x++)
        for(int y = 2; y <= N + 1; y++) {
          for(int t = 0; t < 8; t++) {
            int xx = x + dx[t], yy = y + dy[t];
            df[x][y][i] += df[xx][yy][i - 1]*1.0 / 8.0;
          }
        }
    }

    return df[r + 2][c + 2][K];
  }
};

int main() {
  Solution so;
  cout << so.knightProbability(7,7,2,3) << endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章