Queen N (backtracking method)

51. Queen N – LeetCode

参考:
51. N 皇后 - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/n-queens/solutions/399111/51-n-queenshui-su-fa-jing-dian-wen-ti-xiang-jie-by/

Question description

According to the rules of chess, a queen can attack a piece on the same row or column or on the same diagonal.

The n queen problem studies how to place n queens on the chessboard n×n and use Queens cannot attack each other.

Give you an integer n and return all different n Queen’s Problem solution.

Each solution contains a different n queen problem chess piece placement plan, in which 'Q' and '.' represent the queen and vacancy respectively.

Sample input

Example 1:

Input:n = 4
Output: [[".Q..","...Q","Q..."," ..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: As shown in the figure above, there are two different solutions to the 4-queens problem.

Example 2:

Import:n = 1
Exit:[["Q"]]

hint:

  • 1 <= n <= 9

题解

Restrictions

  • Can't go together
  • Cannot be in the same column
  • Cannot be the same as slash

main idea:

Use the backtracking method to try to traverse all positions, where the for loop controls the columns of the chessboard and the recursive depth controls the rows of the chessboard.

As you can see from the above figure, the height of the tree constructed in the backtracking method is the height of the matrix, and the for loop controls the width of the matrix, which is the width of the tree. As long as we search The leaf nodes of the tree indicate that the reasonable positions of the queens have been found.

Therefore, when using the backtracking method, try to place a queen at each position. Of course, before placing it, we must first determine whether the position is "legal". If we can reach the leaf node, it means we have found a feasible solution and just collect it.

代码

class Solution {
private:
    vector<vector<string>> res;
    //判断当前遍历到的位置是否合法
    bool isValid(int row,int col,vector<string>& chessbord,int n)
    {
        //检查列
        for(int i=0;i<row;i++)
        {
            if(chessbord[i][col]=='Q')
                return false;
        }

        //检查左上角
        for(int i=row-1,j=col-1;i>=0 && j>=0;i--,j--)
        {
            if(chessbord[i][j]=='Q')
                return false;
        }

        //检查右上角
        for(int i=row-1,j=col+1;i>=0 && j<n;i--,j++)
        {
            if(chessbord[i][j]=='Q')
                return false;
        }
        return true;
    }

public:
    void backing(int& n,int row,vector<string>& chessbord)
    {
        if(row==n)
        {
            res.push_back(chessbord);
            return ;
        }

        //for循环控制列
        for(int col=0;col<n;col++)
        {
            //判断当前是否“合法”,如果合法才能放置“皇后”
            if(isValid(row,col,chessbord,n))
            {
                chessbord[row][col]='Q';
                backing(n,row+1,chessbord);//递归控制行
                chessbord[row][col]='.';
            }
        }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<string> chessbord(n,string(n,'.'));
        backing(n,0,chessbord);
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_58158950/article/details/134843829