中国象棋 - 摆上马
2024年12月24日大约 2 分钟
爆搜
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MOD = 1'000'000'000 + 7;
const int MAXN = 100;
const int MAXM = 6;
int n, m; // n 行 m 列
int ans;
int vis[MAXN + 5][MAXM + 5];
int dx[] = {1, -1, 1, -1, 2, -2, 2, -2};
int dy[] = {2, 2, -2, -2, 1, 1, -1, -1};
void dfs(int x, int y)
{
if (y == m + 1)
{
x++;
y = 1;
}
if (x == n + 1)
{
for (int a = 1; a <= n; a++)
for (int b = 1; b <= m; b++)
{
if (!vis[a][b])
continue;
for (int i = 0; i < 8; i++)
{
int aa = a + dx[i];
int bb = b + dy[i];
if (aa < 1 || n < aa ||
bb < 1 || m < bb)
continue;
if (!vis[aa][bb])
continue;
if (dx[i] == 2 || dx[i] == -2)
{
aa = a + dx[i] / 2;
bb = b;
}
else
{
aa = a;
bb = b + dy[i] / 2;
}
if (!vis[aa][bb])
return;
}
}
ans = (ans + 1) % MOD;
return;
}
dfs(x, y + 1);
vis[x][y] = true;
dfs(x, y + 1);
vis[x][y] = false;
}
signed main()
{
cin >> n >> m;
ans = 0;
dfs(1, 1);
cout << ans;
return 0;
}
状压dp
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1'000'000'000 + 7;
int x, y;
// dp[i][sta1][sta2] 前i行,第i行摆放方案为 sta1,第i-1行摆放方案为 sta2,的摆放方案数
int now, pre; // 当前是第now行,上一行是第 pre 行
int dp[2][(1 << 6) - 1 + 5][(1 << 6) - 1 + 5];
// 检查相邻两行是否有冲突
bool check1(int sta1, int sta2)
{
for (int i = 0; i <= y - 1; i++) // 枚举sta1的每个1
{
if ((sta1 & (1 << i)) == 0)
continue;
for (int j = 0; j <= y - 1; j++)
{
if ((sta2 & (1 << j)) == 0)
continue;
// sta1 的 i 的位置有马、sta2 的 j 的位置有马
if (j == i + 2)
{
// sta2 xxjxxxx
// sta1 xxxxixx
if ((sta1 & (1 << i + 1)) && (sta2 & (1 << j - 1)))
continue;
return true;
}
if (j == i - 2)
{
// sta2 xxxxxxjxx
// sta1 xxxxixxxx
if ((sta1 & (1 << i - 1)) && (sta2 & (1 << j + 1)))
continue;
return true;
}
}
}
return false;
}
// 检查间隔一行的两行有没有冲突
bool check2(int sta1, int sta2, int sta3)
{
for (int i = 0; i <= y - 1; i++) // 枚举sta1的每个1
{
if ((sta1 & (1 << i)) == 0)
continue;
for (int j = 0; j <= y - 1; j++)
{
if ((sta3 & (1 << j)) == 0)
continue;
// sta1 的 i 的位置有马、sta3 的 j 的位置有马
if (j == i + 1 || j == i - 1)
{
if ((sta2 & (1 << i)) && (sta2 & (1 << j)))
continue;
return true;
}
}
}
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> x >> y;
memset(dp, 0, sizeof(dp));
// 处理边界情况 前0行,啥都不摆的时候是一种合法方案
dp[0][0][0] = 1;
pre = 0;
now = 1;
int ans = 0;
for (int i = 1; i <= x; i++)
{
// 第i行
for (int sta1 = 0; sta1 <= (1 << y) - 1; sta1++)
{
// 第i-1行
for (int sta2 = 0; sta2 <= (1 << y) - 1; sta2++)
{
dp[now][sta1][sta2] = 0;
if (check1(sta1, sta2))
continue;
// 求 dp[i][sta1][sta2]
// 枚举上上行(i-2)的状态
for (int sta3 = 0; sta3 <= (1 << y) - 1; sta3++)
{
if (check1(sta2, sta3))
continue;
if (check2(sta1, sta2, sta3))
continue;
dp[now][sta1][sta2] += dp[pre][sta2][sta3];
dp[now][sta1][sta2] %= MOD;
}
if (i == x)
{
ans += dp[now][sta1][sta2];
ans %= MOD;
}
}
}
now = 1 - now;
pre = 1 - pre;
}
cout << ans << "\n";
return 0;
}