试题 算法提高 8皇后·改 java 题解 203

问题描述

  规则同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


解题思路:

基本原理同8皇后问题,只是在原基础上增加了约束条件,即要在标有权值的棋盘上的所有摆放方式中找出权值和最大的一种摆放方式。

只需在原始代码基础上维护一个标志二维数组,用来指示每个格子的权值,当每找出一种摆放方式时,就将其权值和累加,最后得出最大权值和。注意测试点的第三个输入中行首有空格,输入方式不能用字符流处理,需要用Scanner处理。

8皇后问题常规方式:

8皇后问题https://blog.csdn.net/weixin_48898946/article/details/121584764icon-default.png?t=LA92https://blog.csdn.net/weixin_48898946/article/details/121584764

java代码:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int[][]flag = new int[8][8];
		for(int i = 0; i < 8; i++) {
			for(int j = 0; j < 8; j++) {
				flag[i][j] = scan.nextInt();
			}
		}
		Queue203 queue = new Queue203(flag);
		queue.dfs(0);
		System.out.println(queue.ans);
	}
}
class Queue203{
	int []arr = new int[8];
	int[][]flag;
	int ans = 0;
	
	public Queue203(int flag[][]) {
		this.flag = flag;
	}
	
	public void dfs(int n) {
		if(n == 8) {
			compare();
			return;
		}
		for(int i = 0; i < 8; i++) {
			arr[n] = i;
			if(isValied(n)) {
				dfs(n + 1);
			}
		}
	}
	
	public void compare() {
		int sum = 0;
		for(int i = 0; i < 8; i++) {
			sum += flag[i][arr[i]];
		}
		if(sum > ans) {
			ans = sum;
		}
	}
	
	public boolean isValied(int n) {
		for(int i = 0; i < n; i++) {
			if(arr[i] == arr[n] || Math.abs(arr[i] - arr[n]) == Math.abs(i - n)) {
				return false;
			}
		}
		return true;
	}
}

提交截图:

おすすめ

転載: blog.csdn.net/weixin_48898946/article/details/121585285