N皇后问题

问题描述:在一个N*N的棋盘上放置N个皇后,且使得每两个之间不能互相攻击,也就是使得每两个不在同一行,同一列和同一斜角线上。

基本思路——回溯法

import java.util.Scanner;

public class N_Queen {
	public static void solve(int n){
		//keep the current position of the queens
		int[] x = new int[n];
		//the index of the current queen
		int i = 0;
		//the number of the answers
		int count = 0;
		
		while(i >= 0){
			if(i == n){
				showAnswer(x);
				count++;
				i--;
				x[i]++;
				continue;
			}
			while(x[i] < n && conflict(x, i, x[i])) x[i]++;
			if(x[i] < n){
				i++;
				if(i < n) x[i] = 0;
			}else{
				i--;
				if(i >=0) x[i]++;
			}
		}
		System.out.printf("Total = %d", count);
	}
	
	private static boolean conflict(int x[], int i, int p){
		for(int k = 0; k < i; k++){
			if(p == x[k] || Math.abs(p - x[k]) == (i - k))
				return true;
		}
		return false;
	}
	
	private static void showAnswer(int[] x){
		for(int i = 0; i < x.length; i++){
			System.out.printf("%d ", x[i] + 1);
		}
		System.out.println();
	}

	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		while(stdIn.hasNextInt()){
			int n = stdIn.nextInt();
			solve(n);
		}
	}
}


测试用例:

5
1 3 5 2 4 
1 4 2 5 3 
2 4 1 3 5 
2 5 3 1 4 
3 1 4 2 5 
3 5 2 4 1 
4 1 3 5 2 
4 2 5 3 1 
5 2 4 1 3 
5 3 1 4 2 
Total = 10
8
1 5 8 6 3 7 2 4 
1 6 8 3 7 4 2 5 
1 7 4 6 8 2 5 3 
1 7 5 8 2 4 6 3 
2 4 6 8 3 1 7 5 
2 5 7 1 3 8 6 4 
2 5 7 4 1 8 6 3 
2 6 1 7 4 8 3 5 
2 6 8 3 1 4 7 5 
2 7 3 6 8 5 1 4 
2 7 5 8 1 4 6 3 
2 8 6 1 3 5 7 4 
3 1 7 5 8 2 4 6 
3 5 2 8 1 7 4 6 
3 5 2 8 6 4 7 1 
3 5 7 1 4 2 8 6 
3 5 8 4 1 7 2 6 
3 6 2 5 8 1 7 4 
3 6 2 7 1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 3 
6 8 2 4 1 7 5 3 
7 1 3 8 6 4 2 5 
7 2 4 1 8 5 3 6 
7 2 6 3 1 4 8 5 
7 3 1 6 8 5 2 4 
7 3 8 2 5 1 6 4 
7 4 2 5 8 1 3 6 
7 4 2 8 6 1 3 5 
7 5 3 1 6 8 2 4 
8 2 4 1 7 5 3 6 
8 2 5 3 1 7 4 6 
8 3 1 6 2 5 7 4 
8 4 1 3 6 2 7 5 
Total = 92


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值