您的位置:首页 > 产品设计 > UI/UE

leetcode 51. N-Queens

2016-07-29 11:02 337 查看
//The n-queens puzzle is the problem of placing n queens on an n×n 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.."]
//]

import java.util.List;
import java.util.ArrayList;

public class Solution {

public static List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<List<String>>();
int[] Qlist = new int
;
Queen(Qlist,0,n,result);
return result;
}

public static void Queen(int[] Qlist, int row ,int n ,List<List<String>> result){	//在第row行中插入Q
if(row == n){													//如果满了就将结果插入result
List<String> temp = new ArrayList<String>();
for(int i = 0;i<n;i++){
String str = "";
for(int j = 0;j<n;j++){
if(Qlist[i] == j){
str = str+"Q";
}else{
str = str+".";
}
}
temp.add(str);
}
result.add(temp);
}
for(int i = 0;i<n;i++){											//没满就判断是否能插入,能的话就插入,不能继续考虑之后的情况
if(isValid(Qlist,row,i)){
Qlist[row] = i;
Queen(Qlist,row+1,n,result);							//递归调用Queen
}
}
}

public static boolean isValid(int[] Qlist, int row, int col){		//判断是否能在第row行的第col列是否能插入Q
for(int i = 0;i<row;i++){
int pos = Qlist[i];									//i是之前确定好的那个行数;row是现在需要插入Q的行数
if(col == pos){										//与之前的同列,返回false
return false;
}
if(col == pos+row-i){								//在之前的右对角线,返回false
return false;
}
if(col == pos-row+i){								//在之前的左对角线,返回false
return false;
}
}
return true;
}

public static void main(String[] args) {
int input = 4;
List<List<String>> result = solveNQueens(input);
System.out.println(result);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: