首页 > 代码库 > leetcode N-Queens

leetcode N-Queens

题目:给定一个n,那么在n*n的棋盘里面放国际象棋的皇后,皇后之间互不在攻击范围。(皇后的攻击范围是她所在位置的哪一行,那一列,和她的正负1的对角线)

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.."]]
思路,利用递归,一行一行地处理,因为每一行只能有一个皇后。并且,每次处理当前行row时,只需要和之前的每一个皇后所在的位置进行是否冲突的判断。如果不冲突,就记录该位置后,继续往下一行递归。
需要注意的问题有:
1.用一个数组记录每一行的皇后的列,因为我们是每一行一行处理,所以一位数组记录皇后的列就行。 perm[i]表示该皇后的坐标为(i,perm[i]);
2.因为我们的行是从0开始的,所以row如果等于n了就说明已经存了n个了,那就是记录一组满足条件的答案;
3.在判断某一行的某一个位置是否放置放皇后的时候,即判断这一行的所有列和之前所有行已经有的皇后是否冲突。
class Solution {public:void solve50(int perm[], int row, int n, vector<vector<string> > &ans){    if (row == n) // 因为row从0开始,说明已经有0到n-1总共n个符合了    {        vector<string> subans;        for (int i = 0; i < n; ++i)        {            string tmps(n, .);            tmps[perm[i]] = Q;            subans.push_back(tmps);        }        ans.push_back(subans);        return;    }    else    {        for (int col = 0; col < n; ++col)//对与第row行的每一个列,进行判断是否符合        {            bool flag = true;            for(int i = 0; i < row; ++i)//对于第row行的每一个列要与之前的每行锁存的王后判断是否冲突            {                if (col == perm[i] || col - perm[i] == row - i || col - perm[i] == i - row)                {// 当前列等于之前的列,或者当前的点和之前的点的斜率为正负1时,为false,否则true进行判断下一行                    flag = false;                }            }            if (flag)//没有冲突,记录当前列数,进入下一行的递归选择            {                perm[row] = col;                solve50(perm, row + 1, n, ans);            }        }    }}vector<vector<string> > solveNQueens(int n){    vector<vector<string> > ans;    //ans.clear();    int perm[n];    //memset(perm, 0, sizeof(perm));    solve50(perm, 0, n, ans);    return ans;}};

 

leetcode N-Queens