码迷,mamicode.com
首页 > 其他好文 > 详细

N-Queens II

时间:2014-06-30 06:24:22      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   数组   

题目

Follow up for N-Queens problem.

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

bubuko.com,布布扣

方法

和上题方法一样,使用回溯法,结构基本相同,只需要返回数量。
    public int totalNQueens(int n) {
        int[] queenAtCol = new int[n];
        int total = getNQueens(0, n, queenAtCol);
        return total;
    }
    public List<String[]> solveNQueens(int n) {
        List <String[]> list = new ArrayList<String[]>();

        return list;
    }
	private int getNQueens(int row, int n, int[] queenAtCol) {
		if (row == n) {
			return 1;
		} else {
			int tempSum = 0;
			for (int col = 0; col < n; col++) {
				if (isValid(row,col,queenAtCol)) {
					queenAtCol[row] = col;
					tempSum += getNQueens(row + 1, n, queenAtCol);
				}
			}
			return tempSum;
		}
	}
	
	private boolean isValid(int row, int col,int[] queenAtCol) {
		//row is valid.
		//column 
		for (int i = 0; i < row; i++) {
			if (queenAtCol[i] == col) {
				return false;
			}
		}
		
		for (int i = 0; i < row; i++) {
			if (i + queenAtCol[i] == row + col) {
				return false;
			}
		}
		
		for (int i = 0; i < row; i++) {
			if (col - row == queenAtCol[i] - i) {
				return false;
			}
		}
		return true;
	}


N-Queens II,布布扣,bubuko.com

N-Queens II

标签:java   leetcode   数组   

原文地址:http://blog.csdn.net/u010378705/article/details/35553863

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!