51. N-Queens (Graph; WFS)

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

思路:WFS,按行递归,在每个递归过程中按列循环,此时可能会有多种选择,所以使用回溯法

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        result.clear();
        string str="";
        for(int i = 0; i<n;i++) str+= ".";
        vector<string> answer(n,str);
        vector<bool> columnFlag(n,false);
        dfs(answer,columnFlag, n, 0);
        return result;
    }
    void dfs(vector<string> &answer, vector<bool> &columnFlag, int n, int depth){ //depth表示行号
        if(depth == n) //递归结束条件
        {
            result.push_back(answer);
            return;
        }

        bool haveAnswer = true;
        for(int i = 0; i < n; i++) //按列循环搜索
        {
            if(columnFlag[i]) continue; //check column

            for (int j = 1; depth-j >= 0 && i-j >= 0; j++) //check upper left diagonal
            {
                if(answer[depth-j][i-j]==‘Q‘)
                {
                    haveAnswer = false;
                    break;
                }
            }
            if(!haveAnswer)
            {
                haveAnswer = true;
                continue;
            }

            for (int j = 1; depth-j >= 0 && i+j <= n-1; j++)  //check upper right diagonal
            {
                if(answer[depth-j][i+j]==‘Q‘)
                {
                    haveAnswer = false;
                    break;
                }
            }
            if(!haveAnswer)
            {
                haveAnswer = true;
                continue;
            }

            //找到一种answer,递归
            answer[depth][i] = ‘Q‘;
            columnFlag[i] = true;
            dfs(answer, columnFlag, n, depth+1);

            //回溯
            answer[depth][i] = ‘.‘;
            columnFlag[i] = false;
        }
    }
private:
    vector<vector<string>> result;
};
时间: 2024-10-09 16:11:55

51. N-Queens (Graph; WFS)的相关文章

118. Pascal&#39;s Triangle (Graph; WFS)

Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] class Solution { public: vector<vector<int> > generate(int numRows) { vector<vector<in

37. Sudoku Solver (Graph; WFS)

Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. class Solut

52. N-Queens II (Graph; WFS)

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. class Solution { public: vector<vector<string>> solveNQueens(int n) { result.clear(); string str=""; for(int

用试探回溯法解决N皇后问题

学校数据结构的课程实验之一. 数据结构:(其实只用了一个二维数组) 算法:深度优先搜索,试探回溯 需求分析: 设计一个在控制台窗口运行的“n皇后问题”解决方案生成器,要求实现以下功能: 由n*n个方块排成n行n列的正方形称为n元棋盘.如果两个皇后位于n元棋盘上的同一行.同一列或同一对角线上,则称它们在互相攻击.现要找出使棋盘上n个皇后互不攻击的布局. 编制程序解决上述问题,以n=6运行程序,输出结果. 算法解释: 首先试探当前行第一个可用的位置(列.对角线没有被占领),摆放皇后之后,试探下一行的

hdu 1429

http://acm.hdu.edu.cn/showproblem.php?pid=1429 一个广搜的简单题吧,不过有意思的事这个题目用到了位运算,还有就是很恶心的MLE 1 #include <stdio.h> 2 #include <string.h> 3 #include <queue> 4 using namespace std; 5 6 int m,n,t; 7 char graph[25][25]; 8 bool vis[24][24][1<<

CodeForces462 A. Appleman and Easy Task

A. Appleman and Easy Task time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you

SAP OLE入门

这个代码是在网上找的,自己进行了学习,入门级的吧 从别的地方COPY了 一些OLE的属性和方法解释 1.ole中如何保存和退出. call method of sheetname 'saveas' exporting #1 = filepath #2 =1. call method of applicationname 'quit'. 2.给sheet重命名. call method of sheetname 'name' = 'sheetname'. 3.创建application. call

java 解析xml 并且将数据自动存入mysql数据库

1 package hello.entity.jiexi_xml; 2 3 import org.jdom.Document; 4 import org.jdom.Element; 5 import org.jdom.JDOMException; 6 import org.jdom.Namespace; 7 import org.jdom.input.SAXBuilder; 8 9 import java.io.FileInputStream; 10 import java.io.IOExcep

QQ登录api

1 <?php 2 namespace Api\Member; 3 class QQConnect{ 4 /** 5 * 获取QQconnect Login 跳转到的地址值 6 * @return array 返回包含code state 7 * 8 **/ 9 public function login($app_id, $callback, $scope){ 10 $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protectio