- 问题描述
规则同8皇后问题,但是棋盘上每格都有一个数字,要求八皇后所在格子数字之和最大。 - 输入说明
一个8*8的棋盘。
数据规模和约定
棋盘上的数字范围0~99 - 输出说明
所能得到的最大数字和 - 输入范例
cpp
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
- 输出范例
cpp
260
感想:写个函数判断row行column列是否可以放皇后;进行dfs,用数组存每行的列数。
代码如下:
cpp
#include <bits/stdc++.h>
using namespace std;
const int n = 8;
vector<vector<int>> chessBoard(n,vector<int>(n));
vector<int> col_pos(n);//某i行的列位置为col_pos[i];
int max_sum = INT_MIN;
//检查第row行、第column列是否可放皇后 (based - 0)
bool isValid(int row,int column) {
for(int i = 0; i<row; ++i) {
if(col_pos[i]==column|| row - i == abs(column - col_pos[i]))
return false;//同列或斜对角已有皇后
}
return true;
}
void dfs(int row,int currentSum) {
if(row == n) { //终止条件
if(currentSum > max_sum)
max_sum = currentSum;
return;
}
for(int col = 0; col<n; ++col) {
if(isValid(row,col)) {
col_pos[row] = col;
dfs(row+1,currentSum + chessBoard[row][col] );
}
}
}
int main() {
for(int i = 0; i<n; ++i) {
for(int j = 0; j<n; ++j) {
cin>>chessBoard[i][j];
}
}
dfs(0,0); // 从第0行开始,初始和为0
cout<<max_sum<<endl;
return 0;
}