题目:

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. shell脚本调试技巧

    shell脚本调试之工具——bashdb http://www.cnblogs.com/itcomputer/p/5011845.html

  2. JavaWeb中五种转发方式(转)

    今天本来是想找一下在jsp中实现转发的方式的,无意中看到了一篇文章,然后稍微综合了把服务器端的转发也包括在内.   1. RequestDispatcher.forward() 是在服务器端起作用,当 ...

  3. HTML、CSS、JS、JQ速查笔记

      一.HTML  1.编写html文件 a.格式 <!DOCTYPE html> <html> <head> <title>标题</title& ...

  4. pycharm tab换为4个空格

    Edit => find => replace 然后勾上 Regex,上一行输入 \t,下一行输入4个空格.

  5. JIRA Plugin Development——Configurable Custom Field Plugin

    关于JIRA Plugin开发的中文资料相当少,这可能还是由于JIRA Plugin开发在国内比较小众的原因吧,下面介绍下自己的一个JIRA Plugin开发的详细过程. 业务需求 创建JIRA IS ...

  6. [转]Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

    string content =[{"id": 3636, "is_default": true, "name": "Unit&q ...

  7. 奇怪的Unrooted Tests错误

    错误如图: 条件如下: Eclipse里的Maven工程. 使用JUnit4(这个是否必须不知,反正我的工程用的4) 修改某个Test类里的方法名,或者增加一个Test方法. 现象: 在MyEclip ...

  8. IOS storyboard(控件器的 生命周期)

    @interface NJTwoViewController () @end @implementation NJTwoViewController // 当控制器的view加载完毕就调用 - (vo ...

  9. 实现带查询功能的ComboBox控件

    实现效果: 知识运用: ComboBox控件的AutoCompleteMode属性 public AutoCompleteMode AutoCompleteMode{get;set;} //属性值为枚 ...

  10. 黑马基础阶段测试题:创建Phone(手机)类,Phone类中包含以下内容:

    package com.swift; public class Phone { private String pinpai; private int dianliang; public String ...