50. N-Queens

The n-queens puzzle is the problem of placing n queens on an nn chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
---
终于懂了,跟CC150上的差不多
我个人觉得很好啊,但是leetcode上跑报run time error,
自己测试倒是能打出正解
再看看!
---
public class Solution {
    public ArrayList<String[]> solveNQueens(int n) {
       
        ArrayList<String[]> rst = new ArrayList<String[]>();
        int[] cols = new int[n];   
        placeQ(n, 0, cols, rst);
        return rst;
    }
    
    
    private void placeQ(int n, int r, int[] cols, ArrayList<String[]> rst){
        
        if(r == n){ //Found one!
        
            String[] ss = new String[n];    
            for(int i=0; i<n; i++){
                char[] chars = new char[n];
                for(int j=0; j<n; j++){
                    if(cols[i] == j)    chars[j] = 'Q';
                    else chars[j] = ',';
                }
                ss[i] = new String(chars); 
            }
            rst.add(ss);
        
        }else{
            for(int c=0; c < n; c++){
                if(checkValid(cols,r,c)){// if Valid
                    cols[r] = c; // place a Q
                    placeQ(n, r+1, cols, rst);// go to next row
                }
            }
        }
    }
    
    private boolean checkValid(int[] cols, int r1, int c1){
        for(int r2=0; r2<r1; r2++){
            int c2 = cols[r2];
            //check if at some col
            if(c2 == c1)    return false;
        }
        return true;
    }
}

 

posted @ 2013-09-22 06:00  LEDYC  阅读(179)  评论(0)    收藏  举报