Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
knight-probability-in-chessboard.cpp 1.00 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-10-01 18:25 +08:00 . Update knight-probability-in-chessboard.cpp
// Time: O(k * n^2)
// Space: O(n^2)
class Solution {
public:
double knightProbability(int N, int K, int r, int c) {
static const vector<pair<int, int>> directions =
{{ 1, 2}, { 1, -2}, { 2, 1}, { 2, -1},
{-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}};
vector<vector<vector<double>>> dp(2, vector<vector<double>>(N, vector<double>(N, 1.0l)));
for (int step = 1; step <= K; ++step) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
dp[step % 2][i][j] = 0;
for (const auto& direction : directions) {
auto rr = i + direction.first;
auto cc = j + direction.second;
if (0 <= cc && cc < N && 0 <= rr && rr < N) {
dp[step % 2][i][j] += 0.125l * dp[(step - 1) % 2][rr][cc];
}
}
}
}
}
return dp[K % 2][r][c];
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助