题目链接:https://leetcode.com/problems/n-queens/
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.."] ]
思路:大学时候学的八皇后问题,两个皇后不能在同一行,同一列,同一斜线上。我采用了一个hash表来存储每一列和每一个对角线是否可放的状态。其中对角线斜率分别为+1和-1,并且截距个数都为(2*n + 1)个。因此我保存了斜率为1不同截距的对角线是否可放的状态和斜率为-1不同截距的对角线是否可放的状态。这样就不用在每一次放皇后的时候都进行计算了。但是这样同样有传递参数的消耗,每次递归都要复制一遍hash表,因此代码的效率虽然可以过,但是并不高效。但是看着还是挺整洁的。
代码如下:
class Solution { public: void DFS(vector<string> vec, int n, int index, vector<vector<bool>> hash) { if(index >= n) { result.push_back(vec); return; } for(int i = 0; i < n; i++) { if(!hash[0][index+i] && !hash[1][index-i+n] && !hash[2][i]) { hash[0][index+i] = true; hash[1][index-i+n] = true; hash[2][i] = true; vec[index][i] = 'Q'; DFS(vec, n, index + 1, hash); vec[index][i] = '.'; hash[0][index+i] = false; hash[1][index-i+n] = false; hash[2][i] = false; } } } vector<vector<string>> solveNQueens(int n) { if(n <= 0) return result; string str(n, '.'); vector<string> vec(n, str); vector<bool> tem(2*n+1, false); //hash表存放了左右对角线,此列是否可放 //第0行代表斜率为-1,截距为(y+x)的对角线是否可放 //第1行代表斜率为1,截距为(y-x+n)的对角线是否可放 //第2行代表第x列是否可放 vector<vector<bool>> hash(3, tem); int index = 0; DFS(vec, n, index, hash); return result; } private: vector<vector<string>> result; };