LeetCode N-Queens
来源:互联网 发布:剑三初始捏脸数据 编辑:程序博客网 时间:2024/06/09 22:35
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.."]]
class Solution {public:vector<vector<string> > solveNQueens(int n) {vector<vector<string> > Array;vector<int> ivec;//初始化数组,使得 ivec[i] = ifor (int i = 0; i < n; ++i) {ivec.push_back(i);}func(Array, ivec, 0, n);return Array;}void func(vector<vector<string> > &Array, vector<int> &ivec, int start, int last) {//判断是否到结尾,是就说明是全排列中的一种if (start == last) {//判断是否满足 皇后之间不能吃,斜对角线和反斜对角线for (int i = 0; i < last; ++i) {for (int j = i + 1; j < last; ++j) {if (i - j == ivec[i] - ivec[j] || j - i == ivec[i] - ivec[j])return;}}//保存皇后位置vector<string> tempvec;for (int i = 0; i < last; ++i) {string str;for (int j = 0; j < ivec[i]; ++j) {str += ".";}str += "Q";for (int j = ivec[i] + 1; j < last; ++j) {str += ".";}tempvec.push_back(str);}Array.push_back(tempvec);return;}//循环加递归 做全排列for (int i = start; i < last; ++i) {swap(ivec[i], ivec[start]);func(Array, ivec, start + 1, last);swap(ivec[i], ivec[start]);}}};
0 0
- 【LeetCode】N-Queens && N-Queens II
- leetcode N-Queens & N-Queens II
- Leetcode: N-Queens && N-Queens II
- 【Leetcode】【python】N-Queens/N-Queens II
- LeetCode: N-Queens II
- LeetCode: N-Queens
- LeetCode : N-Queens
- LeetCode : N-Queens II
- [Leetcode] N-Queens II
- leetcode 72: N-Queens
- LeetCode 38: N-Queens
- 【leetcode】N-Queens II
- 【leetcode】N-Queens
- LeetCode: N Queens II
- [LeetCode]N-Queens
- [LeetCode]N-Queens II
- [leetcode]N-Queens
- [LeetCode] Anagrams、N-Queens
- hiho一下 第八周
- Notepad++不保存文件打开历史与查找替换历史的方法
- 技术面试问题汇总第002篇:猎豹移动反病毒工程师part2
- 一网打尽!200+值得收藏的设计师资源站
- android开发之继承BaseAdapter实现通用数据适配器
- LeetCode N-Queens
- Leetcode 链表 Linked List Cycle II
- codeforces 463E Caisa and Tree 栈+dfs
- C# 基类 派生类 方法隐藏 方法重写
- python小工具:批量替换某个目录下的文件名
- Linux下Apache与Tomcat整合,请求转发【实践成功记录版本】
- C++ 练习笔记
- 关于ios object-c 类别-分类 category 的静态方法与私有变量,协议 protocol 
- STL之multiset中equal_range,multimap中的equal_range,bitset容器,string字符串操作,lambda表达式