历届试题 剪格子
时间限制:1.0s 内存限制:256.0MB
问题描述
如下图所示,3 x 3 的格子中填写了一些整数。
+--*--+--+
|10* 1|52|
+--****--+
|20|30* 1|
*******--+
| 1| 2| 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
10 1 52
20 30 1
1 2 3
样例输出1
3
样例输入2
4 3
1 1 1 1
1 30 80 2
1 1 1 100
1 1 1 1
1 30 80 2
1 1 1 100
样例输出2
10
感觉题目的数据不严密,我的数据有一些情况没考虑到,估计测试数据也没有
3 3
1 1 1
1 2 1
3 1 3
正确的取法应该是
1
1 2
3
输出4
但是我的程序是5,测试了别人的程序也都是5,这种能来回走的情况我也不会写
程序的取法是
1 1 1
1
3
输出5
AC代码:
import java.util.Scanner;
public class Main {
static int[][] map = new int[12][12];
static int[][] visit = new int[12][12];
static int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};
static int sum = 0,m,n,min = Integer.MAX_VALUE;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
m = in.nextInt();
n = in.nextInt();
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
map[i][j] = in.nextInt();
sum += map[i][j];
}
}
if ((sum & 1) == 1) {
System.out.println(0);
}
else {
visit[0][0] = 1;
dfs(0,0,map[0][0]);
if (min != Integer.MAX_VALUE)
System.out.println(min);
else
System.out.println(0);
}
}
private static void dfs(int x, int y,int total) {
if (total > sum / 2)
return;
if (total == sum / 2) {
int temp = 0;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
temp += visit[i][j];
}
}
if (temp < min)
min = temp;
return;
}
for (int i=0; i<4; i++) {
int newx = x + dir[i][0];
int newy = y + dir[i][1];
if (newx < 0 || newx >= n || newy < 0 || newy >= m || visit[newx][newy] == 1)
continue;
visit[newx][newy] = 1;
dfs(newx,newy,total+map[newx][newy]);
visit[newx][newy] = 0;
}
}
}