N-Queens

2023-12-17 19:18
文章标签 queens

本文主要是介绍N-Queens,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

敲到n皇后,mark一下算法,num[i]代表i行的位置是num[i],进行全排列

class Solution {
public:vector<vector<string> > res;void helper(vector<int> &nums, int index, int n) {if(index == n) {bool flag = true;for(int i = 0; i < n && flag; i++) for(int j = i+1; j < n; j++) if((j-i) == abs(nums[j]-nums[i])) {flag = false;break;}if(flag) {vector<string> tmp;for(int i = 0; i < n; i++) {string row(n,'.');row[nums[i]] = 'Q';tmp.push_back(row);}res.push_back(tmp);} }for(int i = index; i < n; i++) {swap(nums[index],nums[i]);helper(nums,index+1; n);swap(nums[index],nums[i]);} }vector<vector<string> > solveNQueens(int n) {res.clear();vector<int> nums(n);for(int i = 0; i < n; i++)nums[i] = i;helper(nums,0,n);return res;}
};



这篇关于N-Queens的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/505531

相关文章

Leetcode204: N-Queens II

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. 有了上一题的解法,简单修改下即可 class Solution {private:int num=0;public: in

【LeetCode】N-Queens II 【九度】题目1254:N皇后问题

N-Queens II Total Accepted: 2737 Total Submissions: 10408 My Submissions Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions.

***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 pu

【PAT】【Advanced Level】1128. N Queens Puzzle (20)

1128. N Queens Puzzle (20) 时间限制 300 ms 内存限制 65536 kB

leetcode-52. N-Queens II

leetcode-52. N-Queens II 题目: > Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. 跟上一题一样,比上一题简单。51-N-Queens I public c

leetcode-51. N-Queens

leetcode-51. 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 t

159.N-Queens II

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. 分析:与上一道题目一样,只不过这个题只需要返回solution的数量即可。 /** Step1:定义一个数组nod

[leetcode]N-Queens

64ms过大集合 class Solution {vector<vector<string>> result;public:bool canPlace(int i, int j, vector<string> &tmp, int n){if(i == 0) return true;for(int k = 0; k < i; k++){if(tmp[k][j] == 'Q') return

leetcode:N-Queens II 【Java】

一、问题描述 Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. 二、问题分析 参考问题leetcode:N-Queens 【Java】 三、算法代码 public cl

leetcode:N-Queens 【Java】

一、问题描述 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-queen