FZU - 2107题解

这是一个ACM题目,描述了曹操逃亡时如何在一个n*4的格子中,使用2*2和不同尺寸的方块填满格子的问题。通过深度优先搜索算法,计算所有可能的排列方式。样例输入输出以及代码实现已给出。

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.

Output

For each test case, print the number of ways all the people can stand in a single line.

Sample Input

2
1
2

Sample Output

0
18

Hint

Here are 2 possible ways for the Hua Rong Dao 2*4.

题意:给你一个n*4的矩阵,要你用一个2*2的方块和任意个1*2,2*1,1*1的方块铺满这个矩阵,问有多少种铺法

思路:n最大为4,可以暴力dfs搜一下,先枚举出2*2放好后的情况,然后从0,0开始放,一共有三种放法对于1*1,1*2,2*1

代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>

using namespace std;
int n, ans;
int s[10][10];
void dfs(int x, int y)
{
    if (x == n) {
        int p = 1;
        for (int i = 0; i < n; i++) {
            for(int j=0;j<4;j++)
                if (s[i][j] == 0) {
                    p = 0;
                    break;
                }
        }
        if (p) {
            ans++; 
        }
        return;
    }
    if (y == 4) {
        dfs(x + 1, 0);
        return;  //表示当前行结束,进入下一行,这个地方第一次忘记return了,结果死循环了
    }
    if (s[x][y]) {
        dfs(x, y + 1);
    }
    else {
        s[x][y] = 1;
        dfs(x, y + 1);
        s[x][y] = 0;
        if (y + 1 < 4 && s[x][y + 1] == 0) {
            s[x][y] = s[x][y + 1] = 1;
            dfs(x, y + 2);
            s[x][y] = s[x][y + 1] = 0;
        }
        if (x + 1 < n && s[x + 1][y] == 0) {
            s[x][y] = s[x + 1][y] = 1;
            dfs(x, y + 1);
            s[x][y] = s[x + 1][y] = 0;
        }
    }
}
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        cin >> n;
        ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 4; j++) {
                if (i + 1 < n&&j + 1 < 4) {
                    memset(s, 0, sizeof(s));
                    s[i][j] = s[i][j + 1] = s[i + 1][j] = s[i + 1][j + 1] = 1;
                    dfs(0,0);
                }
            }
        }
        cout << ans  << endl;
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值