蓝桥杯【历届试题 剪格子】 java版

利用深度优先搜索

import java.util.Scanner;


public class Main{
	
	//存储格子
    static int[][] map;
    //是否已访问
    static int[][] marked;
    //查找当前格子相邻的格子
    static int[][] connect = {{1,0}, {-1,0}, {0,1}, {0,-1}};
    static int sum = 0, m, n;
    static int min = Integer.MAX_VALUE;
    
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		m = sc.nextInt();
		n = sc.nextInt();
		//long startTime = System.currentTimeMillis();
		map = new int[n][m];
		marked = new int[n][m];
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
			{
				map[i][j] = sc.nextInt();
				sum += map[i][j];
			}
		}
		//判断是否能将格子剪成相等的两半
		if(sum % 2 != 0) {
			System.out.println(0);
		}else{
			marked[0][0] = 1;
			dfs(0, 0, map[0][0]);
			System.out.println(min);
		}
		//long endTime = System.currentTimeMillis();
		//System.out.println("程序运行的时间: " + (endTime - startTime) + " ms");
	}
	
	/**
	 * 深度优先搜索
	 * @param x
	 * @param y
	 * @param total
	 */
	public static void dfs(int x,int y,int total)
	{
		if(total > sum / 2) {
			return;
		}
		if(total == sum / 2){
			//符合条件的格子数
			int temp = 0;
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < m; j++) {
					temp += marked[i][j];
				}
			}
			//判断是否是符合条件的最小格子数
			if (temp < min) {
				min = temp;
			}
			return;
		}
		
		// i < 4,最多有四个相邻的格子
		for(int i = 0; i < 4; i++)
		{
			//与(x,y)相邻的(newx, newy)
			int newx = x + connect[i][0];
			int newy = y + connect[i][1];
			
			//判断当前格子是否已被访问 或 是否存在该格子
			if(newx < 0 || newx >= n || newy < 0 || newy >= m || marked[newx][newy] == 1)
				continue;
			marked[newx][newy] = 1;
			dfs(newx, newy, total + map[newx][newy]);
			marked[newx][newy] = 0;
		}
	}
 
}

该博主文章的基础上添加了一些注释,便于理解。

蓝桥杯官网的测试输入及输出

1、input:

3 3
1 1 1
1 8 1
1 1 1

output: 8

2、input:

4 5
10 20 30 1
1 1 40 1 
1 60 50 1 
1 150 1 1 
1 1 1 348

output: 7

扫描二维码关注公众号,回复: 5433500 查看本文章

3、input:

4 4
100 2 2 2
1 30 30 1
30 2 20 1
2 1 1 1
output: 10

猜你喜欢

转载自blog.csdn.net/Sylvia_17/article/details/88212657
今日推荐