问题描述
规则同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
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 { /** * @param args */ public static int sum = 0; public static int max = Integer.MIN_VALUE; public static boolean [] col = new boolean [9]; public static boolean [] row = new boolean [9]; public static int [] hash = new int [9]; public static boolean [] [] bool = new boolean [9][9]; public static int [] [] num = new int [9][9]; public static void main(String[] args) { Scanner sc =new Scanner(System.in); for (int i = 1; i <9; i++) { for (int j = 1; j < 9; j++) { num[i][j]=sc.nextInt(); } } f(1); System.out.println(max); } public static void f(int step){ if(step==9){ max=Math.max(sum, max); return; } for (int i = 1; i <= 8; i++) { if (isConfilct(step, i)) { continue; } else { hash[step] = i; sum+=num[step][i]; f(step + 1); sum-=num[step][i]; hash[step] = -1; } } } private static boolean isConfilct(int row, int column) { //一行一个皇后,第n个皇后也代表着第n行 if(row == 1){//第1行永远不会冲突 return false; } //只需要保证与那些已经就位的皇后不冲突即可 for (int i = 1; i < row; i++) { if (hash[i] == column || ( column - row) == (hash[i] - i) || (row - column)== (i-hash[i]) || (row + column) == (hash[i] + i)) { return true; } } return false; } }