首页 > 学院 > 开发设计 > 正文

蓝桥杯PREV-4 剪格子 (搜索)

2019-11-08 01:30:03
字体:
来源:转载
供稿:网友
  历届试题 剪格子  时间限制:1.0s   内存限制:256.0MB      问题描述

如下图所示,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。

输出格式输出一个整数,表示在所有解中,包含左上角的分割区可能包含的最小的格子数目。样例输入13 310 1 5220 30 11 2 3样例输出13样例输入24 31 1 1 11 30 80 21 1 1 100样例输出2

10

import java.util.Scanner;public class Main {	static int maxn = 10;	static int[][] g = new int[maxn][maxn];	static boolean[][] vis = new boolean[maxn][maxn];	static int m,n,sum,singSum,cnt;	static boolean isOk = false;	static int ans = Integer.MAX_VALUE;	static int[] dr = {-1,0,1,0};	static int[] dc = {0,1,0,-1};	public static void main(String[] args) {		Scanner scan = new Scanner(System.in);		m = scan.nextInt();		n = scan.nextInt();		for(int i=0;i<n;i++){			for(int j=0;j<m;j++){				g[i][j] = scan.nextInt();				sum+=g[i][j];			}		}		if(sum%2!=0){			System.out.PRintln(0);		}else{			dfs(0,0);			if(isOk){				System.out.println(ans);			}else{				System.out.println(0);			}		}	}		public static void dfs(int r,int c){		if(r<0||r>=n||c<0||c>=m)			return;		if(vis[r][c])			return;		if(singSum==sum/2){			isOk = true;			ans = ans>cnt?cnt:ans;			return;		}		vis[r][c] = true;		singSum+=g[r][c];		cnt++;		for(int i=0;i<4;i++){			dfs(r+dr[i],c+dc[i]);		}		cnt--;		singSum-=g[r][c];		vis[r][c] = false;;	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表