leetcode 688. Knight Probability in Chessboard

来源:互联网 发布:美容仪推荐知乎 编辑:程序博客网 时间:2024/05/24 07:35

题目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;}
原创粉丝点击