51. N-Queens

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

51. N-Queens_第1张图片

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..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."] ]

public class Solution {    
    public List> solveNQueens(int n) {
        List> rec = new ArrayList>();
        if(n<=0)
          return rec;
        int[] num = new int[n];
        for(int i=0;i> result,int[] num)
    {
        
        if(start == N)
        {
            List t = new ArrayList();    
            if(isValid(num))
            {
               for(int i = 0; i < N; i++){
         
                 StringBuilder s = new StringBuilder();
                 for(int j = 0; j < N; j++){
                    if(j==num[i])
                         s.append("Q");
                    else
                         s.append(".");
             //    System.out.println(s);
                 }
                 t.add(s.toString());
               }
               result.add(t);
            }
                
        }
        else
        {
            for(int i=start;i

你可能感兴趣的:(51. N-Queens)