题目:

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:
static vector<vector<string> > solveNQueens(int n)
{
vector<vector<string> > ret;
if ( n== ) return ret;
vector<string> tmp;
vector<bool> colUsed(n,false);
vector<bool> diagUsed1(*n-,false);
vector<bool> diagUsed2(*n-,false);
Solution::dfs(ret, tmp, n, colUsed, diagUsed1, diagUsed2);
return ret;
}
static void dfs(
vector<vector<string> >& ret,
vector<string>& tmp,
int n,
vector<bool>& colUsed,
vector<bool>& diagUsed1,
vector<bool>& diagUsed2 )
{
const int row = tmp.size();
if ( row==n )
{
ret.push_back(tmp);
return;
}
string curr(n,'.');
for ( size_t col = ; col<n; ++col )
{
if ( !colUsed[col] && !diagUsed1[col+n--row] && !diagUsed2[col+row] )
{
colUsed[col] = !colUsed[col];
diagUsed1[col+n--row] = !diagUsed1[col+n--row];
diagUsed2[col+row] = !diagUsed2[col+row];
curr[col] = 'Q';
tmp.push_back(curr);
Solution::dfs(ret, tmp, n, colUsed, diagUsed1, diagUsed2);
tmp.pop_back();
curr[col] = '.';
diagUsed2[col+row] = !diagUsed2[col+row];
diagUsed1[col+n--row] = !diagUsed1[col+n--row];
colUsed[col] = !colUsed[col];
}
}
}
};

tips:

深搜写法:

1. 找到一个解的条件是tmp的长度等于n

2. 在一列中遍历每个位置,是否能够放置Q,并继续dfs;返回结果后,回溯tmp之前的状态,继续dfs。

一开始遗漏了对角线也不能在有超过一个Q的条件,补上之后就AC了。

========================================

第二次过这道题,string(n, '.')一直写成了string('.', n),改过来就AC了。

class Solution {
public:
vector<vector<string> > solveNQueens(int n)
{
vector<vector<string> > ret;
if ( n< ) return ret;
vector<string> tmp;
vector<bool> colUsed(n, false);
vector<bool> r2l(*n-, false);
vector<bool> l2r(*n-, false);
Solution::dfs(ret, tmp, n, colUsed, r2l, l2r);
return ret;
}
static void dfs(
vector<vector<string> >& ret,
vector<string>& tmp,
int n,
vector<bool>& colUsed,
vector<bool>& r2l,
vector<bool>& l2r)
{
if ( tmp.size()==n )
{
ret.push_back(tmp);
return;
}
int r = tmp.size();
string row(n, '.');
for ( int i=; i<n; ++i )
{
if ( colUsed[i] || r2l[i-r+n-] || l2r[i+r] ) continue;
colUsed[i] = true;
r2l[i-r+n-] = true;
l2r[i+r] = true;
row[i] = 'Q';
tmp.push_back(row);
Solution::dfs(ret, tmp, n, colUsed, r2l, l2r);
tmp.pop_back();
row[i] = '.';
colUsed[i] = false;
r2l[i-r+n-] = false;
l2r[i+r] = false;
}
}
};

【N-Queens】cpp的更多相关文章

  1. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  2. Hdu 4734 【数位DP】.cpp

    题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...

  3. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  4. 【Permutations II】cpp

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

  5. 【Subsets II】cpp

    题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

  6. 【Sort Colors】cpp

    题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...

  7. 【Sort List】cpp

    题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...

  8. 【Path Sum】cpp

    题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

  9. 【Symmetric Tree】cpp

    题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). F ...

  10. 【Same Tree】cpp

    题目: Given two binary trees, write a function to check if they are equal or not. Two binary trees are ...

随机推荐

  1. centos升级3.10内核到4.4

    为了满足k8s对内核要求,默认Centos 7的内核为3.10建议升级到4.x内核 默认3.10内核升级为4.x内核 rpm -Uvh http://www.elrepo.org/elrepo-rel ...

  2. Redis基础对象

    Redis 中每个对象都由一个 redisObject 结构表示 typedef struct redisObject { //类型 unsigned type:; //编码 unsigned enc ...

  3. android RadioGroup设置某一个被选中

    见码滚 mPriorityRadioGroup.clearCheck(); mStatusRadioGroup.clearCheck(); RadioButton r1 = (RadioButton) ...

  4. log4j.properties中的这句话“log4j.logger.org.hibernate.SQL=DEBUG ”该怎么写在log4j.xml里面呢?

    http://www.cnblogs.com/gredswsh/p/log4j_xml_properties.html 请问:log4j.properties中的这句话“log4j.logger.or ...

  5. MySQL binlog server

    从5.6版本开始,可以利用 mysqlbinlog命令把远程机器的日志备份到本地目录,这样就更加方便快捷的实现一个binlog server. 环境介绍:192.168.56.100是备份服务器,19 ...

  6. xtrabackup支持的engine

    xtrabackup支持的engine 1.InnoDB/XtraDB Hot backup   2.MyISAM with read-lock   3.Archive,CSV with read-l ...

  7. 问题 B: Curriculum Vitae

    问题 B: Curriculum Vitae 时间限制: 1 Sec  内存限制: 128 MB提交: 109  解决: 25[提交][状态][讨论版][命题人:acm4302] 题目描述 Hideo ...

  8. 版本管理工具-SourceSafe

    一.什么是SourceSafe SourceSafe是Micrsoft公司推出的一款支持团队协同开发的配置管理工具,是Visual Studio的套件之一.因为其短小精悍,又继承了微软集成销售的一贯作 ...

  9. java编程基础——从上往下打印二叉树

    题目描述 从上往下打印出二叉树的每个节点,同层节点从左至右打印. 题目代码 /** * 从上往下打印出二叉树的每个节点,同层节点从左至右打印. * Created by YuKai Fan on 20 ...

  10. Bootstrap历练实例:响应式导航

    <!DOCTYPE html><html lang="zh-cn"><head><meta http-equiv="Conten ...