问题描述
如下图所示,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
-------------------------------------------------------------------------------------------------
这道题直接用搜索,可以用递归,用递归返回后一定要将该点访问过变为未访问,我自己在这里苦苦纠结两个钟。
import java.util.Scanner;
public class Main {
static int min = Integer.MAX_VALUE;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();//列数
int m = reader.nextInt();//行数
int[][] array = new int[m][n];
int[][] visited = new int[m][n];//设置点是否被访问
int result = 0;//数组总和
for (int i = 0; i < m; i++) {
for (int s = 0; s < n; s++) {
array[i][s] = reader.nextInt();
result += array[i][s];
}
}
dfs(0, 0, array, visited, 0, result, 0);//搜索
if (min == Integer.MAX_VALUE)
System.out.println(0);
else
System.out.println(min);
}
public static void dfs(int startRow, int startCow, int[][] array, int[][] visited, int now, int result, int num) {
now += array[startRow][startCow];//当前和
num++;//当前已经加入点数
visited[startRow][startCow] = 1;//当前点被访问呢
if (now > result / 2) {
return;
} else if (now == result / 2) {
if (min > num)
min = num;
return;
}
if (startRow < array.length - 1 && visited[startRow + 1][startCow] == 0) {
dfs(startRow + 1, startCow, array, visited, now, result, num);
visited[startRow + 1][startCow] = 0;
}
if (startRow > 0 && visited[startRow - 1][startCow] == 0) {
dfs(startRow - 1, startCow, array, visited, now, result, num);
visited[startRow - 1][startCow] = 0;
}
if (startCow < array[0].length - 1 && visited[startRow][startCow + 1] == 0) {
dfs(startRow, startCow + 1, array, visited, now, result, num);
visited[startRow][startCow + 1] = 0;
}
if (startCow > 0 && visited[startRow][startCow - 1] == 0) {
dfs(startRow, startCow - 1, array, visited, now, result, num);
visited[startRow][startCow - 1] = 0;
}
}
}