首页 > 其他 > 详细

N-Queens

时间:2014-02-06 16:24:28      阅读:388      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1 public class Solution {
 2     public ArrayList<String[]> solveNQueens(int n) {
 3         ArrayList<String[]> res = new ArrayList<String[]>();
 4         if(n<=0) return res;
 5         DFS(n,0,new int[n],res);
 6         return res;
 7     }
 8     public void DFS(int n,int row,int []queenList,ArrayList<String[]>res){
 9         if(row==n){
10             StringBuilder [] sb = new StringBuilder[n];
11             for(int i=0;i<n;i++){
12                 sb[i]=new StringBuilder();
13                 for(int j=0;j<n;j++){
14                     sb[i].append(‘.‘);
15                 }
16             }
17             for(int i=0;i<n;i++){
18                 int colIndex = queenList[i];
19                 sb[i].setCharAt(colIndex,‘Q‘);
20             }
21             String[] output= new String[n];
22             for(int i=0;i<n;i++){
23                 output[i] = sb[i].toString();
24             }
25             res.add(output);
26         }
27         for(int col=0;col<n;col++){
28             if(isValid(queenList,row,col)){
29                 queenList[row] = col;
30                 DFS(n,row+1,queenList,res);
31             }
32         }
33     }
34     public boolean isValid(int []queenList,int row,int col){
35         for(int preRow=0;preRow<row;preRow++){
36             int preCol = queenList[preRow];
37             if(preCol==col) return false;
38             if(Math.abs(preCol-col)==Math.abs(preRow-row))return false;
39         }
40         return true;
41     }
42 }
View Code

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

N-Queens

原文:http://www.cnblogs.com/krunning/p/3538749.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!