问题描述
如下图所示,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。
输出格式
输出一个整数,表示在所有解中,包含左上角的分割区可能包含的最小的格子数目。
思路:
DFS回溯
从左上角开始搜索,直到走过路径和为矩阵所有值总合的一半时,记录格子的数量,用一个used数组记录是否走过当前格子
public class Main {
static int res = Integer.MAX_VALUE;
static int total = 0;
static int[] xd = { -1, 1, 0, 0 };
static int[] yd = { 0, 0, 1, -1 };
static int m;
static int n;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
n = s.nextInt();
m = s.nextInt();
int[][] nums = new int[m][n];
int target = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
nums[i][j] = s.nextInt();
target += nums[i][j];
}
}
if (target % 2 != 0) { //如果不能被2整除,即不合题意
System.out.println(0);
return;
}
target /= 2;
boolean[][] used = new boolean[m][n];
//先初始化
used[0][0] = true;
total += nums[0][0];
dfs(used, nums, target, 0, 0, 1);
if (res == Integer.MAX_VALUE) {
System.out.println(0);
} else {
System.out.println(res);
}
}
public static void dfs(boolean[][] used, int[][] nums, int target, int x, int y, int count) {
if (total >= target) {
if (total == target) {
res = Math.min(res, count);
} else {
return;
}
}
for (int i = 0; i < 4; i++) {
if (x + xd[i] >= 0 && x + xd[i] < m && y + yd[i] >= 0 && y + yd[i] < n) {
if (!used[x + xd[i]][y + yd[i]]) {
used[x + xd[i]][y + yd[i]] = true;
total += nums[x + xd[i]][y + yd[i]];
dfs(used, nums, target, x + xd[i], y + yd[i], count + 1);
used[x + xd[i]][y + yd[i]] = false;
total -= nums[x + xd[i]][y + yd[i]];
}
}
}
}
}