pta:N皇后问题

检查一个如下的 6 x 6 的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行,每列,每条对角线(包括 两条主对角线的所有对角线)上都至多有一个棋子.
在这里插入图片描述

上面的布局可以用序列 2 4 6 1 3 5 来描述,第 i 个数字表示在第 i 行的相应位置有一个棋子,如下: 行号 1 2 3 4 5 6 列号 2 4 6 1 3 5 这只是跳棋放置的一个解.请遍一个程序找出所有跳棋放置的解.并把它们以上面的序列方法输出. 解按字典顺序排列.请输出前 3 个解.最后一行是解的总个数. 特别注意: 对于更大的 N(棋盘大小 N x N)你的程序应当改进得更有效.不要事先计算出所有解然后 只输出,这是作弊.如果你坚持作弊,那么你登陆 USACO Training 的帐号将被无警告删除
输入格式:
一个数字 N (6 <= N <= 13) 表示棋盘是 N x N 大小的.
输出格式:
前四行为前四个解,每个解的两个数字之间用一个空格隔开.第四行只有一个数字,表示解的总数.

import java.util.Scanner;
public class Main{
    static int  []cols;
    static int N;
    static int ways;
    public static void placequeen(int n) {
    	if( n < 1) {
    		return;
    	}
    	cols = new int[N];
    	place(0);
    }
    public static void place(int row) {
    	if(row == cols.length) {
			ways++;
			show();
			return;
		}
    	for(int col = 0;col < cols.length;col++) {
    		if(isvalid(row,col)) {
    			cols[row] = col;
    			place(row + 1);
    		}
    	
    	}
    }
    public static boolean isvalid(int row,int col) {
    	for(int i = 0;i < row;i++) {
    		if(cols[i] == col) {
    			return false;
    		}
    		if(row - i == Math.abs(col -cols[i])){
    			return false;
    		}
    	}
    	return true;
    }
    public static void show() {
    	for(int row = 0;row < cols.length;row++) {
    		for(int col = 0;col < cols.length;col++) {
    			if(cols[row] == col) {
    				System.out.print(col + 1 + " ");
    			}
    		}
    	}
    	System.out.println();
    }
	public static void main(String []args) {
		Scanner in = new Scanner(System.in);
		N = in.nextInt();
		placequeen(N);
		System.out.print(ways);
		
	
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值