LeetCode OJ算法题(五十一):N Queens II

题目:

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

解法:

解法同上一篇N皇后问题,这里只要求输出解的个数,本来用全局变量很容易就解决的,不知道为什么Judge系统死命的报错,对已2皇后问题,本地明明输出0,线上偏偏显示1,最后实在没办法,就把count封装金了内部类中,然后就AC了

O_o!

public class No51_NQueensII {
	class Pair{
		int count;
		public Pair(int i){
			count = i;
		}
	}
	public static void main(String[] args){
		No51_NQueensII m = new No51_NQueensII();
		System.out.println(m.totalNQueens(8));
	}
	public int totalNQueens(int n) {
		Pair p = new Pair(0);
		if(n > 0){
        	char[][] element = new char[n][n];
        	for(int i=0;i<n;i++)
        		for(int j=0;j<n;j++)
        			element[i][j] = '.';
            solve(p, element, n, 0);
        }
		return p.count;
    }
	public static void solve(Pair p, char[][] C, int n, int col){
		for(int i=0;i<n;i++){
			C[i][col] = 'Q';
			if(isLegal(C, i, col)){
				if(col == n-1){
					p.count++;
					C[i][col] = '.';
					continue;
				}
				solve(p, C, n, col+1);
			}
			C[i][col] = '.';
		}
		return;
	}
	public static boolean isLegal(char[][] C, int row, int col){
		for(int j=0;j<col;j++){
			if(C[row][j] == 'Q')
				return false;
		}
		for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
			if(C[i][j] == 'Q')
				return false;
		}
		for(int i=row+1,j=col-1;i<C.length&&j>=0;i++,j--){
			if(C[i][j] == 'Q')
				return false;
		}
		return true;
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值