【leetcode】N-Queens

本文介绍了一种解决N皇后问题的有效方法,通过回溯算法找到所有可能的解决方案。使用了一个一维数组q来记录每行皇后的位置,并定义了判断是否冲突的函数isValid,最后实现了打印解决方案的函数。

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

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.."]
]
 
 
采用q[i]表示第i行的Queen放置的位置
不合法的条件:q[i]==q[level]||abs(q[level]-q[i])==abs(level-i)
 
 1 class Solution {
 2 public:
 3     vector<vector<string> > solveNQueens(int n) {
 4        
 5         vector<int> q(n,-1);
 6         vector<vector<string> > result;
 7         getQueens(0,n,result,q);
 8         return result;
 9     }
10    
11     void PrintQueens(vector<int> &q,vector<vector<string> > &result)
12     {
13         int n=q.size();
14         vector<string> tmp;
15         string str;
16         for(int i=0;i<n;i++)
17         {
18             str="";
19             for(int j=0;j<n;j++)
20             {
21                 if(q[i]==j)str+='Q';
22                 else str+='.';
23             }
24             tmp.push_back(str);
25         }
26        
27         result.push_back(tmp);
28     }
29    
30     void getQueens(int level,int &n,vector<vector<string> > &result,vector<int> &q)
31     {
32         if(level==n)
33         {
34             PrintQueens(q,result);
35             return;
36         }
37         bool flag=false;
38         for(int i=0;i<n;i++)
39         {
40             q[level]=i;
41             if(isValid(q,level))
42             {
43                 getQueens(level+1,n,result,q);
44             }
45             q[level]=-1;
46         }
47     }  
48    
49     bool isValid(vector<int> &q,int &level)
50     {
51  
52         for(int i=0;i<level;i++)
53         {
54             if(q[i]==q[level]||abs(q[level]-q[i])==abs(level-i)) return false;
55         }
56        
57         return true;
58     }
59 };

 

 

转载于:https://www.cnblogs.com/reachteam/p/4213979.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值