【N-Queens】cpp
题目:
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的更多相关文章
- hdu 4739【位运算】.cpp
		
题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...
 - 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~ ...
 - 【Valid Sudoku】cpp
		
题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...
 - 【Permutations II】cpp
		
题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...
 - 【Subsets II】cpp
		
题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...
 - 【Sort Colors】cpp
		
题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...
 - 【Sort List】cpp
		
题目: Sort a linked list in O(n log n) time using constant space complexity. 代码: /** * Definition for ...
 - 【Path Sum】cpp
		
题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
 - 【Symmetric Tree】cpp
		
题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). F ...
 - 【Same Tree】cpp
		
题目: Given two binary trees, write a function to check if they are equal or not. Two binary trees are ...
 
随机推荐
- Android Broadcast Receive
			
Broadcast Receive 广播接收(Broadcast Receive)为android的四大组件之一.主要用于监听广播消息,并做出响应.与应用程序中监听事件相比而言,该监听事件为全局监听. ...
 - 1)实际时间(real time): 从command命令行开始执行到运行终止的消逝时间;  2)用户CPU时间(user CPU time): 命令执行完成花费的用户CPU时间,即命令在用户态中执行时间总和;  3)系统CPU时间(system CPU time): 命令执行完成花费的系统CPU时
			
1)实际时间(real time): 从command命令行开始执行到运行终止的消逝时间: 2)用户CPU时间(user CPU time): 命令执行完成花费的用户CPU时间,即命令在用户态中执行时 ...
 - 利用binlog2sql解析mysqlbinlog row行日志
			
binlog2sql 项目作者:曹单锋 github项目地址:https://github.com/danfengcao/binlog2sql 也可在github.com上搜索“binlog2sql” ...
 - DDL与DML语句
			
1. DDL语句 SQL语句:结构化查询语句,使用SQL与数据库“沟通”,完成相应的数据库操作. l DDL:数据定义语言,用来维护数据库对象 1.1 创建表 Ø CREATE:创建表 演示:创建员工 ...
 - Ubuntu 16.04 开启休眠功能
			
因为休眠功能在部分计算机无法正常工作,所以Ubuntu默认是不开启休眠功能. 要想开启休眠功能先进行如下测试: 1.先检查是否有交换分区(swap),如果有确认交换分区至少和实际可用内存一样大. 2. ...
 - CAsyncSocket  create创建套接字失败
			
解决方法: 在继承CAsyncSocket 类的子类的构造函数中加入以下代码: if (!AfxSocketInit()) AfxMessageBox(IDP_SOCKETS_INIT_FAILED) ...
 - android RadioGroup设置某一个被选中
			
见码滚 mPriorityRadioGroup.clearCheck(); mStatusRadioGroup.clearCheck(); RadioButton r1 = (RadioButton) ...
 - 感谢我的python老师
			
Python自动化开发(金角大王版) http://www.cnblogs.com/alex3714/articles/5885096.html
 - 在maven项目中 配置代理对象远程调用crm
			
1 在maven项目中配置代理对象远程调用crm 1.1 在项目的pom.xml中引入CXF的依赖 <dependency> <groupId>org.apache.cxf&l ...
 - JavaScript中的confirm的用法
			
confirm()方法用于显示一个带有指定消息和ok以及取消按钮的对话框confirm(message,ok,cancel); message:表示在弹出框的对话框中现实的文本信息如果用户点击确定按钮 ...