暴力搜索
package dfs;
import java.util.Arrays;
import java.util.Scanner;
public class 方格填数 {
static Scanner s = new Scanner(System.in);
static int n = s.nextInt(),sum = 0;
static int[] ghy = new int[n*n];//读取输入数组
static int[][] ans = new int[n][n];//记录答案
static int[] hang = new int[n];//行
static int[] lie = new int[n];//列
static int count = 0;//左对角线
static int count2 = 0;//右对角线
static boolean[] flag = new boolean[n*n];//标记是否走过
public static void main(String[] args) {
for (int i = 0; i < n * n; i++) {
ghy[i] = s.nextInt();
sum += ghy[i];
}
sum = sum/n;
Arrays.sort(ghy);
dfs(0);
}
static void dfs(int u){
if (u == n * n) {
for (int i = 0; i < n; i++) {
if (!(hang[i] == sum && lie[i] == sum)) {//判断行和列
return;
}
}
//如果行和列都通过了在判断对角线,这里要注意,判断完要把count重置为0
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
count += ans[i][j];
}
if ((i + j) == n - 1) {
count2 += ans[i][j];
}
}
}
if(count == sum && count2 ==sum) {
System.out.println(sum);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(ans[i][j] + " ");
}
System.out.println();
}
System.exit(0);//直接终止程序
}
count2 =count=0;//重置count,不然不正确的答案的count会累加
return;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(!flag[i*n + j]) {
flag[i*n + j] = true;//标记为走过
ans[u/n][u%n] = ghy[i * n + j];//i*n + j是代表第几个,u/n得出的是第几行,不可以直接用i
hang[u/n] += ghy[i * n + j];
lie[u%n] += ghy[i * n + j];
dfs(u + 1);
回溯
flag[i*n + j] = false;
ans[u/n][u%n] = 0;
hang[u/n] -= ghy[i * n + j];
lie[u%n] -= ghy[i * n + j];
}
}
}
}
}