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

Leetcode51 N后

时间:2017-12-15 20:49:36      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:track   char   nbsp   []   class   etc   span   solution   ali   

class Solution {
    
     public static int[] x;
     public static int sum=0;
     public static char[][] board;
    
    public List<List<String>> solveNQueens(int n) {
         x =new int[n];
         for(int i=0;i<n;i++){
             x[i]=0;
         }
         board = new char[n][n];
         for(int i=0;i<n;i++){
             for(int j=0;j<n;j++) {
                 board[i][j] = ‘.‘;
             }
         }
         List<List<String>> res = new ArrayList<List<String>>();
        BackTrack(0,board,res,n);
        return res;
    }
     public static void BackTrack( int k ,char[][] board,List<List<String>> res,int n){
         if(k==n){
             res.add(construct(board,n));
             return;
         }
         for(int i=0;i<n;i++){
             x[k] = i; 
             if(isValid(k)){
                board[k][x[k]] = ‘Q‘;
                BackTrack(k+1,board,res,n);
             }
             board[k][x[k]] = ‘.‘;
         }

    }
    
    public static boolean isValid(int t){
        for(int j=0;j<t;j++){
            if( Math.abs(j-t) == Math.abs(x[j] -x[t]) || x[j] == x[t] )
                return false;
        }
        return true;
    }
    
    public static List<String> construct(char[][] board,int n){
           List<String> res = new LinkedList<String>();
           for(int i=0;i<n;i++){
               String s = new String(board[i]);
               res.add(s);
           }
           return res;
    }
       
}
    
    

 

Leetcode51 N后

标签:track   char   nbsp   []   class   etc   span   solution   ali   

原文地址:http://www.cnblogs.com/vector11248/p/8044718.html

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