算法提高 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




很簡單dfs,直接上代碼



package cn.lml.base.www;


import java.util.Scanner;


public class BaHuangHou {
static Scanner s=new Scanner(System.in);
static int mase[]=new int[8];
static int vis[][]=new int[8][8];
static boolean ok[][]=new boolean[8][8];
static int count=0;
static int max=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
vis[i][j]=s.nextInt();
}
}
f(0);
//System.out.println(count);
System.out.println(max);
}
public static void f(int num){
int i,j;
if(num==8){
int b=findMax(ok);
if(b>max){
max=b;
}
count++;
return;
}
for( i=0;i<8;i++){
mase[num]=i;
for(j=0;j<num;j++){
if(mase[num]==mase[j]||num+mase[num]==j+mase[j]||num-mase[num]==j-mase[j]){

break;
}
}
if(num==j){
ok[num][i]=true;
f(num+1);
ok[num][i]=false;
}
}

}
public static int findMax(boolean[][] oks){
int sum=0;
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
if(oks[i][j]==true){
sum+=vis[i][j];
}
}

}
return sum;
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章