蓝桥杯练习13:剪格子

问题 1432: [蓝桥杯][2013年第四届真题]剪格子

原题链接:[蓝桥杯][2013年第四届真题]剪格子
解题思路:容易想到dfs。

package 蓝桥;

import java.util.Scanner;

public class Main {
	static int m;// 列,注意题目先给m
	static int n;// 行
	static int[][] map;//存储图
	static boolean[][] vis;//标记是否访问过
	static int sum_other = 0;//记录没走过的格子值之和
	static int min = Integer.MAX_VALUE / 2;//初始化最小格子数
	static int[][] dir = new int[][] { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };// 左右上下,注意数组和坐标系不同

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		m = sc.nextInt();
		n = sc.nextInt();
		map = new int[n][m];
		vis = new boolean[n][m];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				map[i][j] = sc.nextInt();
				sum_other += map[i][j];
			}
		}
		dfs(0, 0, 0, sum_other);
		System.out.println(min);
		sc.close();
	}

	static void dfs(int i, int j, int sum, int sum_other) {
		sum += map[i][j];
		sum_other -= map[i][j];
		vis[i][j] = true;
		if (sum > sum_other) {
			vis[i][j]=false;
			return;
		}
		if (sum == sum_other) {
			int res=0;
			for(int k=0;k<n;k++) {
				for(int p=0;p<m;p++) {
					if(vis[k][p]) {
						res+=1;
					}
				}
			}
			if (min > res) {
				min = res;
			}
			return;
		}
		for (int k = 0; k < 4; k++) {
			int x = i + dir[k][0];
			int y = j + dir[k][1];
			if (x >= 0 && x < n && y >= 0 && y < m && !vis[x][y]) {
				dfs(x, y, sum, sum_other);//从四个方向探索
			}
		}
		vis[i][j] = false;//四个方向都走不通,释放这个格子
	}

}


发布了42 篇原创文章 · 获赞 1 · 访问量 1632

猜你喜欢

转载自blog.csdn.net/qq_44467578/article/details/104449043
今日推荐