Cracking the coding interview--Q8.8

本文介绍了一个经典问题——八皇后问题的解决方案。通过使用回溯算法来找出在8×8的棋盘上摆放八个皇后的方法,确保任意两个皇后不在同一行、列或对角线上。代码示例详细展示了如何实现这一算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

原文:

Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.

译文:

写一个算法打印八皇后在棋盘中所有使任意2个皇后不能处于同一行,同一列或是对角线上的摆法。

解答

这是经典的八皇后问题,首先了解八皇后问题的规则,在8*8国际象棋棋盘上,要求在每一行放置一个皇后,且能做到在竖方向,斜方向都没有冲突。国际象棋的棋盘如下图所示:

3c3f32555ed870c1b745aeb2

用回溯算法。对于每一行,列,检查皇后不攻击不违反所需的条件。

为此,我们需要存储的列女王在每一行只要我们完成它。让ColumnForRow[]是商店的数组每行的列号。
给出的检查,需要三个条件:
在同一列:ColumnForRow[i]= = ColumnForRow[j]

在同一对角线:(ColumnForRow[i]——ColumnForRow[j])= =(i - j)或(ColumnForRow[j],ColumnForRow[i])= =(i - j),代码如下:

class Q8_8{
	public static int columForRow[]=new int[8];
	public static int count=0;
	public static boolean check(int row){
		for(int i=0;i<row;i++){
			int diff=Math.abs(columForRow[i]-columForRow[row]);
			if(diff==0||diff==row-i) return false;
		}
		return true;
	}
	public static void placeQueen(int row){
		if(row==8){
			print();
			count++;
			return;
		}
		for(int i=0;i<8;i++){
			columForRow[row]=i;
			if(check(row)){
				placeQueen(row+1);
			}
		}
	}
	public static void print(){
		for(int i=0;i<8;i++){
			for(int j=0;j<8;j++){
				if(j==columForRow[i]) System.out.print("1 ");
				else System.out.print("0 ");
			}
			System.out.println();
		}
		System.out.println();
	}
	public static void main(String[] args){
		placeQueen(0);
		System.out.println(count);

	}
}

---EOF---




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值