蓝桥杯 剪格子

问题描述

如下图所示,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
样例输入2
4 3
1 1 1 1
1 30 80 2
1 1 1 100
样例输出2
10

*****************************************************************************************

思路:从左上角开始dfs,然后记录包含arr[0][0]在内的格子的个数,最后取最小值即可。由于oj的测试数据给的格子范围都不大,几乎都是秒出的。
import java.util.Scanner;
import java.util.TreeSet;

public class 剪格子 {
	static int[][] arr = null;
	static boolean[][] map = null;
	static int flag = 0;
	static int count = 0;
	static TreeSet<Integer> record = new TreeSet<Integer>();
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int y = sc.nextInt();
		int x = sc.nextInt();
		arr = new int[x][y];
		map = new boolean[x][y];
		for (int i = 0; i < x; i++) {
			for (int j = 0; j < y; j++) {
				arr[i][j] = sc.nextInt();
				flag += arr[i][j];
			}
		}
		dfs(0, 0, 0);
		System.out.println(record.first());

	}

	// 0 上 1右 2下 3左
	static void dfs(int sum, final int x, final int y) {
		if (sum == flag / 2) {
			count++;
			calcSum();
			return;
		}
		if (sum > flag) {
			return;
		}
		int newX = 0, newY = 0;
		for (int i = 0; i < 4; i++) {
			if (!canGo(x, y, i))
				continue;
			newX = x;
			newY = y;
			if (i == 0) {
				newX -= 1;
			}
			if (i == 1) {
				newY += 1;
			}
			if (i == 2) {
				newX += 1;
			}
			if (i == 3) {
				newY -= 1;
			}
			// 可以深入
			if (!map[newX][newY]) {
				map[x][y] = true;
				dfs(sum + arr[x][y], newX, newY);
				map[x][y] = false;
			}
		}
	}

	// 0 上 1右 2下 3左
	static boolean canGo(int x, int y, int aim) {
		if (x == 0 && aim == 0)
			return false;
		if (x == arr.length - 1 && aim == 2)
			return false;
		if (y == 0 && aim == 3)
			return false;
		if (y == arr[0].length - 1 && aim == 1)
			return false;
		return true;
	}
	
	static void calcSum() {
		boolean flag = map[0][0];
		int sum = 0;
		for (int i = 0; i < map.length; i++) {
			for (int j = 0; j < map[0].length; j++) {
				if (map[i][j] == flag)
					sum++;
			}
		}
		record.add(sum);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值