算法提高 8皇后·改
/* 算法提高 8皇后·改 问题描述 规则同8皇后问题,但是棋盘上每格都有一个数字,要求八皇后所在格子数字之和最大。 输入格式 一个8*8的棋盘。 输出格式 所能得到的最大数字和 样例输入 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 48 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 样例输出 260 数据规模和约定 棋盘上的数字范围0~99 */ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); for (int i = 1; i < b.length; i++) { for (int j = 1; j < b[0].length; j++) { b[i][j] = sc.nextInt(); } } sc.close(); dfs(1); System.out.println(sum); } static int a[] = new int[9]; static int sum; static int b[][] = new int[9][9]; static void dfs(int n) { for (int i = 1; i <= 8; i++) { a[n] = i; if (check() && n < 8) { dfs(n + 1); } if (check() && n == 8) { sum(); } a[n] = 0; } } static void sum() { int sum2 = 0; for (int i = 1; i <= 8; i++) { sum2 += b[a[i]][i]; } sum = Math.max(sum, sum2); } static boolean check() { for (int i = 1; i < a.length - 1; i++) for (int j = i + 1; j < a.length; j++) { if (a[i] != 0 && a[j] != 0 && (a[i] == a[j] || (Math.abs(a[j] - a[i]) == j - i))) { return false; } } return true; } }