八皇后问题递归解法(Java实现)

问题描述

问题表述为:在8×8格的国际象棋上摆放8个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。

public class EightQueen
{
    
    
	static int n = 8;
	// 用一个数组来储存数据
	// 数组下标表示行,数组的元素表示列
	static int[] list = new int[n];
	// 计数
	static int count = 0;
	
	public static void main(String[] args)
	{
    
    
		Search(list, 0, n);
		System.out.println(count);
	}
	
	public static boolean Check(int[] list, int row)
	// 检查是否满足条件
	{
    
    
		for(int i = 0;i < row;i++)
		{
    
    
			// 如果两皇后在同一列
			if(list[i] == list[row])
			{
    
    
				return false;
			}
			// 两皇后在同一对角线上,即斜率为 1
			else if(Math.abs(row - i) == Math.abs(list[i] - list[row]))
			{
    
    
				return false;
			}
		}
		
		return true;
	}
	
	// 往棋盘里放置皇后
	public static void Search(int[] list, int row, int n)
	{
    
    
		// 递归终止条件
		if(row == n)
		{
    
    
			Print(list);
			return;
		}
		for(int i = 0;i < n;i++)
		{
    
    
			list[row] = i;
			if(Check(list, row))
			{
    
    
				// 往棋盘下一行放置皇后
				Search(list, row + 1, n);
			}
		}
	}
	
	// 打印结果
	public static void Print(int[] list)
	{
    
    
		for(int row = 0;row < n;row++)
		{
    
    
			for(int col = 0;col < n;col++)
			{
    
    
				if(list[row] == col)
				{
    
    
					// 1表示皇后的位置
					System.out.print("1 ");
				}
				else
				{
    
    
					System.out.print("0 ");
				}
			}
			System.out.println();
		}
		count++;
		System.out.println();
	}
}



最终结果为92种。

猜你喜欢

转载自blog.csdn.net/x5445687d/article/details/123193494