51. N-Queens, leetcode

来源:互联网 发布:音频压缩算法 编辑:程序博客网 时间:2024/05/28 18:45

题目:

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

代码及思路:(回溯的递归方法)15ms AC

class Solution {public:int place(int k)//k 表示行数;函数的意思是,查看(k,x[k])是否可以放皇后{for (int i = 0; i < k ; i++)//当前行是k - 1if (abs(k - i) == abs(x[k] - x[i]) || x[i] == x[k]) return 0;return 1;}void Backtrak(int t){if (t > n - 1){sum++;vector<string> temp;string a(n,'.');for(auto p : x){    a[p] = 'Q';    temp.push_back(a);    a[p] = '.';}ans.push_back(temp);}else{for (int i = 0; i < n; i++){x[t] = i;if (place(t))Backtrak(t + 1);}}}vector<vector<string>> solveNQueens(int in) {vector<int> vec(in, -1);x = vec;n = in;Backtrak(0);return ans;}private:vector<int> x;//注意1:这里不能写作vector<int> x(); 否则认为x是一个函数;并且在这里对x进行初始化也将报错。int n;//注意2:这里n是可以初始化的int sum = 0;vector<vector<string>> ans;};

代码及思路2:(回溯的栈方法)

待续

总结:

1,对于回溯问题,最好找一个数据结构存储解的集合。比如这里的x[i],表示第i行的第j列可以放皇后。即用
数组存储每行皇后的位置
2,其中一个微小笔误,浪费了好长时间去排查。为什么用这么长时间才排查出来,是因为排查方法不当,
所以以后写代码出现错误,不要害怕,打开IDE设置合适的断点,很容易就可以找出来的。

0 0
原创粉丝点击