两个易错: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);
}
}