题目:
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.."] ]
题解:
C++版:
class Solution { private: vector<vector<string>> results; public: vector<vector<string> > solveNQueens(int n) { if(n == 0) return results; vector<int> location(n, -1); trace(location, 0, n); return results; } void trace(vector<int>& location, int level, int n) { if(level == n) { vector<string> res(n, string(n, '.')); for(int i = 0; i < n; i++) { res[i][location[i]] = 'Q'; } results.push_back(res); return; } for(int i = 0; i < n; i++) { if(isValid(location, level, i)) { location[level] = i; trace(location, level + 1, n); location[level] = -1; } } } bool isValid(vector<int>& location, int row, int col) { for(int i = 0; i < row; i++) { if(location[i] == col || abs(row - i) == abs(location[i] - col)) return false; } return true; } };
public class Solution { private List<String[]> results; public List<String[]> solveNQueens(int n) { if(n == 0) return results; int[] location = new int[n]; for(int i = 0; i < n; i++) location[i] = -1; trace(location, n, 0); return results; } private void trace(int[] location, int n, int level) { if(level == n) { String[] res = new String[n]; for(int i = 0; i < n; i++) { StringBuilder s = new StringBuilder(); for(int j = 0; j < n; j++) { if( j == location[i]) s.append("Q"); else s.append("."); } res[i] = s.toString(); } results.add(res); return; } for(int i = 0; i < n; i++) { if(isValid(location, level, i)) { location[level] = i; trace(location, n, level + 1); location[level] = -1; } } } private boolean isValid(int[] location, int row, int col) { for(int i = 0; i < row; i++) { if(location[i] == col || Math.abs(row - i) == Math.abs(location[i] - col)) return false; } return true; } }
class Solution: # @return a list of lists of string def solveNQueens(self, n): results = [] if n == 0 or n == 2: return results location = [-1 for i in range(n)] def trace(location, n, level): if level == n: res = [('.' * n) for i in range(n)] for i in range(n): res[i] = res[i][0:location[i]] + 'Q' + res[i][location[i] + 1:] results.append(res) return for i in range(n): if isValid(location, level, i): location[level] = i trace(location, n, level+1) location[level] = -1 def isValid(location, row, col): for i in range(row): if location[i] == col or abs(row - i) == abs(location[i] - col): return False return True trace(location, n, 0) return results