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

leetcode 51. N-Queens

2017-07-24 23:43 429 查看
leetcode 51. N-Queens

N-queen N 皇后问题: python解法:

dfs, 建立树,然后根据建立的树获取答案

class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def dfs(queen, xy_dif, xy_sum):
p = len(queen)
if p==n:
result.append(queen)
return None;
for q in range(n):
if q not in queen and p-q not in xy_dif and p+q not in xy_sum:
dfs(queen+[q], xy_dif + [p-q], xy_sum + [p+q])
result = []
dfs([],[],[])
return [ ["."*i + "Q" + "."*(n-i-1) for i in sol] for sol in result]


java 解法:果然还是python 容易写算法一些:
public class Solution {
public List<List<String>> solveNQueens(int n) {
char[][] board = new char

;
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>>();
dfs(board, 0, res);
return res;
}

private void dfs(char[][] board, int colIndex, List<List<String>> res) {
if(colIndex == board.length) {
res.add(construct(board));
return;
}

for(int i = 0; i < board.length; i++) {
if(validate(board, i, colIndex)) {
board[i][colIndex] = 'Q';
dfs(board, colIndex + 1, res);
board[i][colIndex] = '.';
}
}
}

private boolean validate(char[][] board, int x, int y) {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < y; j++) {
if(board[i][j] == 'Q' && (x + j == y + i || x + y == i + j || x == i))
return false;
}
}

return true;
}

private List<String> construct(char[][] board) {
List<String> res = new LinkedList<String>();
for(int i = 0; i < board.length; i++) {
String s = new String(board[i]);
res.add(s);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: