/*我们沿着图中的红色线剪开,得到两个部分,每个部分的数字和都是60。
本题的要求就是请你编程判定:对给定的m x n 的格子中的整数,是否可以分割为两个部分,使得这两个区域的数字和相等。
如果存在多种解答,请输出包含左上角格子的那个区域包含的格子的最小数目。
如果无法分割,则输出 0
程序输入输出格式要求:
程序先读入两个整数 m n 用空格分割 (m,n<10)
表示表格的宽度和高度
接下来是n行,每行m个正整数,用空格分开。每个整数不大于10000
程序输出:在所有解中,包含左上角的分割区可能包含的最小的格子数目。
例如:
用户输入:
3 3
10 1 52
20 30 1
1 2 3
则程序输出:
3
再例如:
用户输入:
4 3
1 1 1 1
1 30 80 2
1 1 1 100
则程序输出:
10*/
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int m, n, minStep, sum;
int dir[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};
int map[10][10];
bool vis[10][10];
bool judgeBound(int x, int y)
{
if(x<0 || x>=m || y<0 || y>=n)
return false;
return true;
}
void DFS(int x, int y, int tot, int cnt)
{
tot += map[x][y];
if(tot == sum)
{
if(cnt+1 < minStep)
minStep = cnt+1;
return;
}
if(tot > sum || cnt+1 > minStep)
return;
for(int i = 0; i < 4; ++i)
{
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(judgeBound(tx, ty) && !vis[tx][ty] && tot+map[tx][ty] <= sum)
{
vis[x][y] = true;
DFS(tx, ty, tot, cnt+1);
vis[x][y] = false;
}
}
}
int main()
{
while(~scanf("%d%d", &n, &m))
{
sum = 0;
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
{
scanf("%d", &map[i][j]);
sum += map[i][j];
}
if(sum & 1 || (map[0][0]<<1) > sum)
printf("0\n");
else
{
sum >>= 1;
minStep = 0x7fffffff;
memset(vis, false, sizeof(vis));
DFS(0, 0, 0, 0);
if(minStep == 0x7fffffff)
printf("0\n");
else
printf("%d\n", minStep);
}
}
return 0;
}
/*
3 3
10 1 52
20 30 1
1 2 3
3
3 3
24 1 1
6 24 1
1 1 1
2
4 3
1 1 1 1
1 30 80 2
1 1 1 100
10
9 9
2 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
极限数据出不来结果
*/