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

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

Problem statement:

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

Solution:

As a classical, N-Queens typically is a DFS problem. The solution follows DFS template. 

According to the rules to place the queen, they can not in the same column, we do not need to keep a vector which records if a position is visited or not. 

class Solution {public:    vector
> solveNQueens(int n) { vector
> solu_sets; vector
solu(n, string(n, '.')); NQueens(solu_sets, solu, 0, n, n); return solu_sets; }private: void NQueens(vector
>& solu_sets, vector
& solu, int row, int col, int n){ if(row == n){ solu_sets.push_back(solu); return; } for(int i = 0; i < col; i++){ if(isvalid(solu, row, i, n)){ solu[row][i] = 'Q'; NQueens(solu_sets, solu, row + 1, col, n); solu[row][i] = '.'; } } return; } bool isvalid(vector
& solu, int row, int col, int n){ for(int i = row - 1, left = col - 1, right = col + 1; i >= 0; i--, left--, right++){ // vertically/diagonal/anti-diagonal conflict if(solu[i][col] == 'Q' || (left >= 0 && solu[i][left] == 'Q') || (right < n && solu[i][right] == 'Q')){ return false; } } return true; }};

转载于:https://www.cnblogs.com/wdw828/p/6839305.html

你可能感兴趣的文章
最全的分区类型及详解
查看>>
Python 类中__init__()方法中的形参与如何修改类中属性的值
查看>>
9.1.3 前端 - HTML body标签 - 文本样式
查看>>
ACID属性
查看>>
cnpm不是内部命令的解决方案:配置环境变量
查看>>
7系列FPGA远程更新方案-QuickBoot(转)
查看>>
导出帐号和权限脚本
查看>>
markdown公式编辑参考
查看>>
利用运行时给模型赋值
查看>>
归并排序求逆序对
查看>>
SQL2008用sql语句给字段添加说明
查看>>
JavaScript的对象创建
查看>>
树形DP(统计直径的条数 HDU3534)
查看>>
python学习之路(25)
查看>>
c++中拷贝构造函数、默认无参构造函数、析构函数的理解
查看>>
ActiveReports 报表控件官方中文入门教程 (3)-如何选择页面报表和区域报表
查看>>
kaggle竞赛
查看>>
区块链入门教程
查看>>
域 搭建OU 组织单元
查看>>
静态方法中调用非静态方法
查看>>