`
hcx2013
  • 浏览: 82664 次
社区版块
存档分类
最新评论

N-Queens II

 
阅读更多

Follow up for N-Queens problem.

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

 

public class Solution {
	private int num = 0;
	public int totalNQueens(int n) {
    	solve(0, n, new int[n]);
    	return num;
    }

	private void solve(int i, int n, int[] positions) {
		if (i == n) {
			num++;
		} else {
			for (int j = 0; j < n; j++) {
				positions[i] = j;
				if (validate(i, positions)) {
					solve(i+1, n, positions);
				}
			}
		}
	}
	private boolean validate(int maxRow, int[] positions) {
        for (int i = 0; i < maxRow; i++) {
            if (positions[i] == positions[maxRow]
                    || Math.abs(positions[i] - positions[maxRow]) == maxRow - i) 
                return false;
        }
        return true;
    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics