博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
51. N-Queens
阅读量:4260 次
发布时间:2019-05-26

本文共 1523 字,大约阅读时间需要 5 分钟。

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..”]
]

思路:N皇后问题可以看做一个N维数组的全排列问题,主要做法是回溯

bool isNQueens(vector
& res){ for (int i = 0; i < res.size(); i++){ for (int j = i + 1; j < res.size(); j++){ if (i - j == res[i] - res[j] || i - j == res[j] - res[i])return false; } } return true;}void dfs_SolveNQueens(vector
& res, int pos, vector
>& tt){ if (pos == res.size()){ if (isNQueens(res)){ vector
temp(res.size(), string(res.size(), '.')); for (int i = 0; i < res.size(); i++){ temp[i][res[i]] = 'Q'; } tt.push_back(temp); } return; } for (int i = pos; i < res.size(); i++){ swap(res[i], res[pos]); dfs_SolveNQueens(res, pos + 1, tt); swap(res[i], res[pos]); }}vector
> solveNQueens(int n) { vector
> res; if (n == 0)return res; vector
temp; for (int i = 0; i < n; i++)temp.push_back(i); dfs_SolveNQueens(temp, 0, res); return res;}
你可能感兴趣的文章
基于比较的排序算法的最优下界---NlogN
查看>>
Paxos协议学习---2.由3大条件证明一致性
查看>>
Paxos协议学习---3.Paxos Made Simple
查看>>
C/C++输入输出
查看>>
泸州NGN属南气矿工程----华为s2600磁盘阵列问题解决
查看>>
泸州属南气矿----配置S2600磁盘阵列报错:There is no master controller.
查看>>
SQL 调优1
查看>>
OA报账规范(出差专用)
查看>>
生产库快速关闭数据库
查看>>
差异增量备份和累积增量备份的差别
查看>>
ASM 无法发现候选磁盘组----grid 11.2.0.3 asm 自检通不过 prvf-5184
查看>>
ASM 无法发现候选磁盘组----丢失的ASM磁盘组 ASM的磁盘组无法挂载
查看>>
Oracle 10g配置单向stream流复制,完整记录
查看>>
ORA-00845 MEMORY_TARGET not supported on this system
查看>>
ORA-00257: archiver error --11GR2 RAC 设置归档路径和开启flashback
查看>>
奕新集团项目--Oracle 源RAC ---目标 RAC GG 搭建 11.2.3 版本 双向同步
查看>>
What is SCAN in Oracle 11g R2 RAC
查看>>
关于Recycle Bin是什么以及实验
查看>>
Linux搭建时间同步服务器
查看>>
ORA-12541: TNS:no listener
查看>>