Hua Rong Dao
Cao Cao was hunted down by thousands of enemy soldiers when he escaped from Hua Rong Dao. Assuming Hua Rong Dao is a narrow aisle (one N*4 rectangle), while Cao Cao can be regarded as one 2*2 grid. Cross general can be regarded as one 1*2 grid.Vertical general can be regarded as one 2*1 grid. Soldiers can be regarded as one 1*1 grid. Now Hua Rong Dao is full of people, no grid is empty.
There is only one Cao Cao. The number of Cross general, vertical general, and soldier is not fixed. How many ways can all the people stand?
Input
There is a single integer T (T≤4) in the first line of the test data indicating that there are T test cases.
Then for each case, only one integer N (1≤N≤4) in a single line indicates the length of Hua Rong Dao.
2 1 2Sample Output
0 18Hint
Here are 2 possible ways for the Hua Rong Dao 2*4.
直接dfs搜索,注意return的位置
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int vis[10][10];
int n,ans,flag;
bool judge(int x,int y){
if(x >= 1 && x <= n && y >= 1 && y <= 4 && !vis[x][y])
return true;
return false;
}
void dfs(int counts){
if(counts == 4 * n && flag){//放满并且有一个2*2的矩形
ans++;
return ;
}
if(counts >= 4 * n) return;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= 4; j++){
if(judge(i,j) && judge(i,j+1) && judge(i+1,j) && judge(i+1,j+1) && !flag){
flag = 1;
vis[i][j] = vis[i][j+1] = vis[i+1][j] = vis[i+1][j+1] = 1;
dfs(counts+4);
flag = 0;
vis[i][j] = vis[i][j+1] = vis[i+1][j] = vis[i+1][j+1] = 0;
}
if(judge(i,j) && judge(i,j+1)){
vis[i][j] = vis[i][j+1] = 1;
dfs(counts+2);
vis[i][j] = vis[i][j+1] = 0;
}
if(judge(i,j) && judge(i+1,j)){
vis[i][j] = vis[i+1][j] = 1;
dfs(counts+2);
vis[i][j] = vis[i+1][j] = 0;
}
if(judge(i,j)){
vis[i][j] = 1;
dfs(counts+1);
vis[i][j] = 0;
return;//因为1*1的都是相同的,通过递归放置return回来后如果继续执行肯定会继续达到通过递归放置的位置所以就重复了
}
}
}
}
int main(){
int t;
scanf("%d",&t);
while(t--){
ans = flag = 0;//flag表示是否放下了一个2*2的矩形
memset(vis,0,sizeof(vis));
scanf("%d",&n);
dfs(0);
printf("%d\n",ans);
}
return 0;
}
本文探讨了一个经典的华容道问题变种:曹操被敌军包围,如何计算所有可能的站位方式使得曹操(2*2方格)能够在华容道(N*4矩形)中被完全围住。文章提供了详细的算法实现,使用深度优先搜索(DFS)来遍历所有可能的布局。
120

被折叠的 条评论
为什么被折叠?



