|

楼主 |
发表于 2020-4-13 18:31:21
|
显示全部楼层
本帖最后由 糖逗 于 2020-4-14 15:39 编辑
相似题型:面试题 08.12. 八皇后
- 设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。
- 注意:本题相对原题做了扩展
- 示例:
- 输入:4
- 输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
- 解释: 4 皇后问题存在如下两个不同的解法。
- [
-  [".Q..",  // 解法 1
-   "...Q",
-   "Q...",
-   "..Q."],
-  ["..Q.",  // 解法 2
-   "Q...",
-   "...Q",
-   ".Q.."]
- ]
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/eight-queens-lcci
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- #include<string>
- #include<vector>
- #include<iostream>
- using namespace std;
- bool valid(vector<int>& pos, int x, int y){
- for(int i = 0; i < pos.size(); i++){
- if(i == x || y == pos[i] || x + y == i + pos[i] || x + pos[i] == y + i)return false;
-
- }
- return true;
- }
- void dfs(int n, int x, vector<int>& pos, vector<string>& temp, vector<vector<string> >& res){
- if(x == n) res.push_back(temp);
- for(int y= 0 ; y < n; y ++){
- if(valid(pos, x, y)){
- temp[x][y] = 'Q';
- pos.push_back(y);
- dfs(n, x+1, pos, temp, res);
- pos.pop_back();
- temp[x][y] = '.';
- }
- }
- }
- vector<vector<string> > solution(int n){
- vector<vector<string> > res;
- vector<string>temp (n, string(n, '.'));
- vector<int> pos;
- dfs(n, 0, pos, temp, res);
- return res;
- }
- int main(void){
- int n;
- cin >> n;
- vector<vector<string> > res = solution(n);
- for(int i = 0; i < res.size(); i++){
- for(int j = 0; j < res[i].size(); j++){
- cout << res[i][j] << endl;
- }
- cout << endl;
- cout << "------------------" << endl;
- }
- return 0;
- }
-
复制代码
参考链接:
1.x + y == i + pos[i] || x + pos[i] == y + i 可参见链接:https://leetcode-cn.com/problems ... u-zu-ji-lu-dui-jia/ |
|