[leetcode] N-Queens II

Follow up for N-Queens problem.

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

https://oj.leetcode.com/problems/n-queens-ii/

思路:参考N-Queens,只统计个数即可。

 

public class Solution {
	public int totalNQueens(int n) {
		if (n <= 0)
			return 0;
		int[] perm = new int[n];
		slove(perm, 0, n);

		return count;
	}

	private int count = 0;

	private void slove(int[] perm, int cur, int n) {
		if (cur == n) {
			count++;
		} else {
			int i;
			for (i = 0; i < n; i++) {
				int j;
				boolean ok = true;
				for (j = 0; j < cur; j++) {
					if (perm[j] == i || perm[j] - j == i - cur
							|| perm[j] + j == i + cur)
						ok = false;
				}
				if (ok) {
					perm[cur] = i;
					slove(perm, cur + 1, n);
				}

			}

		}

	}

	public static void main(String[] args) {
		System.out.println(new Solution().totalNQueens(8));

	}
}

 

第二遍记录:判断冲突的条件搞错了, cur和i代表什么不要搞错了。

  cur代表当前要填皇后的行, i表示第cur行要在第i列填入。

  所以j循环条件是 j<cur,不是i。

public class Solution {
    private int count;
    public int totalNQueens(int n) {
        if(n<=0)
            return 0;
        int[] perm = new int[n];    
        totalCount(perm,0);
        return count;    
    }
    
    private void totalCount(int[] perm,int cur){
        if(cur==perm.length){
            count++;
            return;   
        }
        
        for(int i=0;i<perm.length;i++){
            
            boolean ok= true;
            for(int j=0;j<cur;j++){
                if(perm[j]==i||perm[j]-j==i-cur||perm[j]+j==i+cur){
                    ok=false;
                    break;
                }
                
            }
            if(ok){
                perm[cur]=i;   
                totalCount(perm,cur+1);
            }
        }
        
        
    }
    
    
}

 

 

 

posted @ 2014-06-26 20:04  jdflyfly  阅读(136)  评论(0编辑  收藏  举报