八皇后问题
蒜头君在和朋友下国际象棋,下的时候突发奇想,在国际象棋棋盘的每个格子上写下 11 到 9999内的数字,又拿出了珍藏已久的 88 个皇后棋子。国际象棋中的皇后可以将同一行、同一列和同一对角线上的对方棋子吃掉。小蒜头在想,怎么摆放这 88 个皇后的位置才能让她们不能互相攻击,同时这 88 个皇后占的格子上的数字总和最大。
蒜头君来求助热爱算法的你了,你能帮她算出答案吗?
输入格式
每个棋盘有 6464 个数字,分成 88 行 88 列输入,就如样例所示。棋盘上每一个数字均小于 100100。
输出格式
输出一个最大的总和
样例输入
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
import java.util.Scanner; public class Main { static int n = 8; static int max; static int[][] chess = new int[8][8]; static boolean[] a = new boolean[8]; static boolean[] zheng = new boolean[15]; static boolean[] fan = new boolean[15]; private static void dfs(int step, int x) { if(step >= n) { if(x > max) max = x; return; } for(int i = 0; i < n; i ++) { if(a[i] == false && zheng[i + step] == false && fan[i - step + n - 1] == false) { zheng[i + step] = true; fan[i - step + n - 1] = true; a[i] = true; dfs(step + 1, x + chess[step][i]); a[i] = false; fan[i - step + n - 1] = false; zheng[i + step] = false; } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); for(int i = 0; i < chess.length; i ++) { for(int j = 0; j < chess[0].length; j ++) { chess[i][j] = sc.nextInt(); } } dfs(0, 0); System.out.println(max); } }