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

【Leetcode】:51. N-Queens 问题 in JAVA

2016-04-25 19:16 543 查看
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.

[

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

  "...Q",

  "Q...",

  "..Q."],

 ["..Q.",  // Solution 2

  "Q...",

  "...Q",

  ".Q.."]

]

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

这道题的难度为Hard,确实需要花一番功夫才能做出来,仍然采用递归的思路可以方便的解题

首先需要一个简便的方法来表示Q的放置,一个N长的数组就可以解决 int
,例如int[0]=1表示在Q放在第1行的第2列,int[2]=3表示在Q放在第3行的第4列。

为了方便表达,需要一个自定义函数private boolean isValid(int[] queenList, int row, int col)函数返回是否可以在指定的行列放置Q,这里有一个前提就是该指定行上面的Q的放置是合法的。

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

public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<List<String>>();
int[] queenList = new int
; //第i个位置存放的数表示row行时,Q的列
placeQueen(queenList, 0, n, res);//在第0行放Q
return res;
}
private void placeQueen(int[] queenList, int row, int n, List<List<String>> res) {
//如果已经填满,就生成结果
if (row == n) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < n; i++) {
String str = "";
for (int col = 0; col < n; col++){
if(queenList[i] == col) {
str += "Q";
} else {
str += ".";
}
}
list.add(str);
}
res.add(list);
}
for (int col = 0; col < n; col++) {//循环每一列
if (isValid(queenList, row, col)) { //如果在该列放入Q不冲突的话
queenList[row] = col;
placeQueen(queenList, row + 1, n, res);
}
}
}

private boolean isValid(int[] queenList, int row, int col) {
for (int i = 0; i < row; i++) {
int pos = queenList[i];
if (pos == col) { //和新加入的Q处于同一列
return false;
}
if (pos + row - i == col) { //在新加入的Q的右对角线上
return false;
}
if (pos - row + i == col) { //在新加入的Q的左对角线上
return false;
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java