动态规划+剪枝+回溯 蓝桥杯 2013 Java A 9题

两个易错:1、行列(m、n)z注意别输反了 2、没找到记得输出0

import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改

public class Main {
static int bestRes[][] = new int [100][100];
	static int res [][];
	static int resStep[][];
	static int total = 0;
	static int m ;
	static int n ;
	static int ans = Integer.MAX_VALUE;
	static void def(int x,int y,int steps,int sum ) {
		if(x>m||y>n||x<1||y<1||resStep[x][y]==1)
			return;
		if(sum>total/2)
			return;
		else if(sum==total/2) {
			if(ans>steps) {
				ans = steps;
				for(int i = 1;i<=m;i++) {
					for(int j =1;j<=n;j++) {
						bestRes[i][j] = resStep[i][j];
					}
				}
			}
			return;
		}
		resStep[x][y] = 1;//回溯
		def(x+1,y,steps+1,sum+res[x][y]);
		
		def(x,y+1,steps+1,sum+res[x][y]);
	
		def(x-1,y,steps+1,sum+res[x][y]);
	
		
		def(x,y-1,steps+1,sum+res[x][y]);
		resStep[x][y] = 0;
	}
	
	public static void main(String []args) {
		Scanner scan = new Scanner(System.in); 
		n = scan.nextInt();
		 m = scan.nextInt();
		
		res=new int [100][100];
		resStep=new int [100][100];
		for(int i =1;i<=m;i++) {
			for(int j = 1;j<=n;j++) {
				res[i][j] = scan.nextInt();
				total+=res[i][j];
			}
		}
	
		//System.out.println(total);
		def(1,1,0,0);
	       if(ans!=Integer.MAX_VALUE)//没找到
		 System.out.println(ans);
	       else
	    	System.out.println(0);   
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值