解題思路
DP 狀態為目前格子、上一步方向、已轉彎數、採樣點數。起點用無方向旗標並先算採樣。
向右或向下到非障礙格時,若舊方向存在且不同就加一轉彎;落點為 * 再加一採樣,超出目標即捨棄。
每條單調路徑有唯一的逐格轉移,抵達終點且兩計數恰好符合才相加;起終點重合時無方向初態自然保留。
C++ 稀疏 map 時間 O(hw(T+1)(C+1) log((T+1)(C+1))),Python 期望 O(hw(T+1)(C+1));空間 O(hw(T+1)(C+1))。
Step-by-step animation
教學例子:教學2×2空板、T=1、C=0,起點尚無方向。
步驟 1 / 3
步驟 1
教學2×2空板、T=1、C=0,起點尚無方向。
..
..
- 狀態
- 初態1
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int h, w, T, C;
cin >> h >> w >> T >> C;
vector<string> g(h);
for (auto &s : g)
cin >> s;
const int M = 1000000007;
using Key = tuple<int, int, int>;
vector<vector<map<Key, long long>>> dp(h, vector<map<Key, long long>>(w));
if (g[0][0] != '#' && (g[0][0] == '*') <= C)
dp[0][0][{2, 0, g[0][0] == '*'}] = 1;
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++)
for (auto [key, ways] : dp[i][j]) {
auto [d, t, c] = key;
for (int nd = 0; nd < 2; nd++) {
int x = i + (nd == 1), y = j + (nd == 0);
if (x >= h || y >= w || g[x][y] == '#')
continue;
int nt = t + (d != 2 && d != nd), nc = c + (g[x][y] == '*');
if (nt <= T && nc <= C) {
auto &z = dp[x][y][{nd, nt, nc}];
z = (z + ways) % M;
}
}
}
long long ans = 0;
for (auto [key, ways] : dp[h - 1][w - 1])
if (get<1>(key) == T && get<2>(key) == C)
ans = (ans + ways) % M;
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。