N-Queens

本文介绍了一种经典问题——N皇后问题,目标是在一个N×N的棋盘上放置N个皇后,确保它们互不攻击。文章详细阐述了使用回溯法的解题思路,包括检查位置的有效性,以及时间复杂度O(N!)和空间复杂度O(N^2)的分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

Example 1:

Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above

Example 2:

Input: n = 1
Output: [["Q"]]

Intuition

The N-Queens problem is a classic problem in which the task is to place N queens on an N x N chessboard in such a way that no two queens attack each other. The problem can be solved using backtracking. The idea is to explore all possible configurations of queen placements on the chessboard and backtrack whenever a conflict is encountered.

Approach

Backtracking Function (backtrack):

The backtracking function takes a parameter r representing the current row.
In the base case, if r is equal to n, it means queens have been successfully placed in all rows, and a valid solution is found. In this case, create a copy of the current board configuration and add it to the result (res).
Otherwise, iterate over all columns (c) in the current row and check if placing a queen at position (r, c) is valid. The validity is checked by ensuring that the column (c), the positive diagonal (r + c), and the negative diagonal (r - c) are all available. If valid, mark the positions as occupied and proceed to the next row (r + 1).
After the recursive call, backtrack by removing the queen from the current position.
Initialization:

Initialize sets (col, posdiag, negdiag) to keep track of occupied columns, positive diagonals, and negative diagonals.
Initialize an empty list res to store the final result.
Create a 2D board (board) filled with dots ('.') to represent the chessboard.
Backtracking Invocation:

Invoke the backtrack function with the initial row index (r = 0).
Return Result:

Return the final result (res), which contains all distinct solutions to the N-Queens puzzle.

Complexity

  • Time complexity:

The time complexity is O(N!), where N is the number of queens to be placed. The backtracking algorithm explores all possible configurations, and there are N choices for each row.

  • Space complexity:

The space complexity is O(N^2) due to the space required for the chessboard (board) and the sets (col, posdiag, negdiag). The recursion stack also contributes to the space complexity.

Code

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        col = set()
        posdiag = set()
        negdiag = set()

        res = []
        board = [['.'] * n for i in range(n)]

        def backtrack(r):
            if r == n:
                copy = [''.join(row) for row in board]
                res.append(copy)
                return
            
            for c in range(n):
                if c in col or (r + c) in posdiag or (r - c) in negdiag:
                    continue
                
                col.add(c)
                posdiag.add(r + c)
                negdiag.add(r - c)
                board[r][c] = 'Q'

                backtrack(r + 1)
                
                col.remove(c)
                posdiag.remove(r + c)
                negdiag.remove(r - c)
                board[r][c] = '.'
        
        backtrack(0)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值