Eight queens problem recursive solution (Java implementation)

Problem Description

The problem is stated as: place 8 queens on an 8×8 grid chess so that they cannot attack each other, that is, any two queens cannot be in the same row, column or slant, how many ways are there . Gauss believes that there are 76 schemes. In 1854, different authors published 40 different solutions in the Chess Magazine in Berlin. Later, someone used graph theory to solve 92 results.

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();
	}
}



The final result is 92 kinds.

Guess you like

Origin blog.csdn.net/x5445687d/article/details/123193494