N Queens

题目描述:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard 

such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle(难题).

Each solution contains a distinct(不同)board configuration of the n-queens' placement,
where 'Q' and '.' both indicate(象征) a queen and an empty space respectively.
   
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

思路:这个是很经典的问题,重点在于如何判断是否符合摆放规则,因为是逐行摆放且每行只放一个,所以可以自动忽略对行的判断,因为是从上往下放,所以只需要判断该行上面的列和对角线是否已经摆放过棋子即可。

public class N_Queens {
	 public static ArrayList<String[][]> solveNQueens(int n) 
	 {
		 ArrayList<String[][]> result=new ArrayList<String[][]>();
		 String board[][]=new String[n][n];
		 for(int i=0;i<n;i++)
		 {
			for(int j=0;j<n;j++)
			{
				board[i][j]=".";
			} 
		 }
		 solve(result,board,n,0);
		 return result;
	 }
	 public static void solve(ArrayList<String[][]> al,String board[][],int n,int line)
	 {
		 if(line==n)
		 {
			 String result[][]=new String[n][n];
			 for(int i=0;i<n;i++)
				 for(int j=0;j<n;j++)
					 result[i][j]=board[i][j];
			 al.add(result);
		 }
		 else
		 {
			//对每一行的每一列进行枚举
			for(int i=0;i<n;i++)
			{
				if(check(board,n,line,i))
				{
					board[line][i]="Q";
				}
				else
				{
					continue;
				}
				solve(al,board,n,line+1);
				board[line][i]=".";
			}
		 }
	 }
	 public static boolean check(String board[][],int n,int line,int column)
	 {
		 for(int i=line-1;i>=0;i--)
		 {
			if(board[i][column].equals("Q"))
			{
				return false;
			}
		 }
		 for(int i=line-1,j=column-1;i>=0&&j>=0;i--,j--)
		 {
			 if(board[i][j].equals("Q"))
			 {
				 return false;
			 }
		 }
		 for(int i=line-1,j=column+1;i>=0&&j<n;i--,j++)
		 {
			 if(board[i][j].equals("Q"))
			 {
				 return false;
			 }
		 }
		return true; 
	 }
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		for(int i=0;i<solveNQueens(n).size();i++)
		{
			for(int j=0;j<solveNQueens(n).get(i).length;j++)
			{
				for(int k=0;k<solveNQueens(n).get(i).length;k++)
				{
					System.out.print(solveNQueens(n).get(i)[j][k]+" ");
				}
				System.out.println("\n");
			}
			System.out.println("+++++++++++++++++++++++++++++");
		}
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值