蓝桥杯历届试题 剪格子【DFS】

问题描述

如下图所示,3 x 3 的格子中填写了一些整数。

+--*--+--+
|10* 1|52|
+--****--+
|20|30* 1|
*******--+
| 1| 2| 3|
+--+--+--+

我们沿着图中的星号线剪开,得到两个部分,每个部分的数字和都是60。

本题的要求就是请你编程判定:对给定的m x n 的格子中的整数,是否可以分割为两个部分,使得这两个区域的数字和相等。

如果存在多种解答,请输出包含左上角格子的那个区域包含的格子的最小数目。

如果无法分割,则输出 0。

输入格式

程序先读入两个整数 m n 用空格分割 (m,n<10)。

表示表格的宽度和高度。

接下来是n行,每行m个正整数,用空格分开。每个整数不大于10000。

输出格式

输出一个整数,表示在所有解中,包含左上角的分割区可能包含的最小的格子数目。

样例输入1

3 3
10 1 52
20 30 1
1 2 3

样例输出1

3

思路:我的写法可是真暴力了,也就暴力杯能够水过去,就是在每个位置都搜一下,每次都记录最短的数目,最后输出答案就可以了。

#include<set>
#include<map>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 5000;
int mp[12][12], d[2][4] = {1, 0, -1, 0, 0, 1, 0, -1};
bool vis[12][12];
int sum = 0, ans = inf;
int m, n;
void dfs(int x, int y, int num, int val)
{
    if(x > m || x < 1 || y > n || y < 1 || vis[x][y])
        return;
    val += mp[x][y];
    if(val == sum/2)
        ans = min(ans, num);
    vis[x][y] = true;
    for(int i = 0; i < 4; ++i)
    {
        int xx = x + d[0][i];
        int yy = y + d[1][i];
        dfs(xx, yy, num + 1, val);
    }
    vis[x][y] = false;
}
int main()
{
    cin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        for(int j = 1; j <= n; ++j)
        {
            cin >> mp[i][j];
            sum += mp[i][j];
        }
    }
    if(sum % 2 == 1)
    {
        cout << "0" << endl;
        return 0;
    }
    else
    {
        dfs(1, 1, 1, 0);
        if(ans == inf)
        {
            for(int i = 1; i <= m; ++i)
            {
                for(int j = 1; j <= n; ++j)
                {
                    dfs(i, j, 1, 0);
                }
            }
        }
        if(ans == inf)
            cout << "0" << endl;
        else
            cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41785863/article/details/88769021