题目地址:


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.

Example:

Input: 4
Output: [[".Q..",  // Solution 1"...Q","Q...","..Q."],["..Q.",  // Solution 2"Q...","...Q",".Q.."]
]

Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.


这道题是经典的N皇后问题,可以用回溯法解决
注意:Python和Java的解法是一样的,我看不懂C++的解法
大佬的python解法如下:

class Solution:def solveNQueens(self, n: int) -> List[List[str]]:def DFS(queens, xy_dif, xy_sum):p = len(queens) # p is the index of rowif p == n:result.append(queens)return Nonefor q in range(n): # q is the index of col # queens stores those used cols, for example, [0,2,4,1] means these cols have been used# xy_dif is the diagonal 1# xy_sum is the diagonal 2if q not in queens and p - q not in xy_dif and p + q not in xy_sum:DFS(queens + [q], xy_dif + [p - q], xy_sum + [p + q])result = []DFS([], [], [])return [["." * i + "Q" + "." * (n - i - 1) for i in sol] for sol in result]

大佬的java解法如下:

//use backtracking algorithm to try out the positions
//for every level, there are n options to place. try them as in a small for loop
//from that level, go down, for each path, choose the next level node. check whether it's valid or not. if valid, then go on backtracking. (use a tmplist to store location info)
//if not valid, return.
//return condition is that it reached the final level and all queens placed
//question: what does it mean that two queens don't attach each other?
//怎么来看是否valid, 如何标记 每当加一个数字进去,相应的三个方向用数组来记录 mark下
//One puts a queen on the board and that immediately excludes one column, one row and two diagonals for the further queens placement.
//go back if not validclass Solution {//boolean array to track whether it can be placed or not.//when one queen is placed on board, board[level][i], its column, its two diagonals are occupied.boolean[] col;boolean[] D45;boolean[] D135; //这个D135的好难想  public List<List<String>> solveNQueens(int n) {//create a grid and fill it. char[][] board = new char[n][n];for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {board[i][j] = '.'; }}col = new boolean[n];D45 = new boolean[2 * n];D135 = new boolean[2 * n]; //default to false. meaning can place. true means occupied/can't place. List<List<String>> res = new ArrayList<>();if(n <= 0) return res; backtrack(board, res, 0, n);return res;         }public void backtrack(char[][] board, List<List<String>> res, int level, int n) {//if(level > n) return; if(level == n) {addSolution(res, board); return; }for(int i = 0; i < n; i++) {//if(!canPlace(board[level][i])) return;if(col[i] || D45[level + i] || D135[i - level + n - 1]) continue;  //确实是应该continue, return直接出去了, 这在for loop里面呢 //45度角的是 row + col. //135是col - row. //otherwise, continueboard[level][i] = 'Q'; col[i] = true;D45[level + i] = true;D135[i - level + n - 1] = true; backtrack(board, res, level + 1, n);board[level][i] = '.'; //复原 unmark for other routes. col[i] = false;D45[level + i] = false;D135[i - level + n - 1] = false;         }              }public void addSolution(List<List<String>> res, char[][]board) {List<String> tmp = new ArrayList<>(); for(char[] level : board) {tmp.add(String.valueOf(level)); //charArray to string. String.valueOf()}res.add(tmp); }}

大佬的c++解法如下:

class Solution {public:vector<vector<string>> solveNQueens(int n) {vector<vector<string>> res;vector<string> solution(n,std::string(n,'.'));solve(res,solution,n,0,0,0);return res;}void solve(vector<vector<string>> &res,vector<string> &solution,int n,int row, int ld ,int rd){if(((1<<n)-1)==row){res.push_back(solution);return;}int D= ((1<<n)-1)&(~(row|rd|ld));while(D){int bit=D&(~D+1);solution[rowcount(row)][n-colcount(bit)]='Q';solve(res,solution,n,row|bit,(ld|bit)<<1,(rd|bit)>>1);solution[rowcount(row)][n-colcount(bit)]='.';D=D^bit;}}int rowcount(int row){int cnt=0;while(row){cnt+=row&0x1;row>>=1;}return cnt;}int colcount(int col){int cnt=0;while(col){cnt++;col>>=1;}return cnt;}
};

正常的C++解法如下:

class Solution {public:std::vector<std::vector<std::string> > solveNQueens(int n) {std::vector<std::vector<std::string> > res;std::vector<std::string> nQueens(n, std::string(n, '.'));std::vector<int> flag_col(n, 1), flag_45(2 * n - 1, 1), flag_135(2 * n - 1, 1);solveNQueens(res, nQueens, flag_col, flag_45, flag_135, 0, n);return res;}
private:void solveNQueens(std::vector<std::vector<std::string> > &res, std::vector<std::string> &nQueens, std::vector<int> &flag_col, std::vector<int> &flag_45, std::vector<int> &flag_135, int row, int &n) {if (row == n) {res.push_back(nQueens);return;}for (int col = 0; col != n; ++col)if (flag_col[col] && flag_45[row + col] && flag_135[n - 1 + col - row]) {flag_col[col] = flag_45[row + col] = flag_135[n - 1 + col - row] = 0;nQueens[row][col] = 'Q';solveNQueens(res, nQueens, flag_col, flag_45, flag_135, row + 1, n);nQueens[row][col] = '.';flag_col[col] = flag_45[row + col] = flag_135[n - 1 + col - row] = 1;}}
};

LeetCode 51. N-Queens--回溯法 pyhon,java,c++解法相关推荐

  1. LeetCode之单词搜索(回溯法求解)

    题目 给定一个 m x n 二维字符网格 board 和一个字符串单词 word .如果 word 存在于网格中,返回 true :否则,返回 false . 单词必须按照字母顺序,通过相邻的单元格内 ...

  2. LeetCode 47 全排列 II -- 回溯法

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/permutations-ii 题意: 给定一个可包含重复数字的序列 nums ,按任意顺序 返 ...

  3. 【LeetCode】46 全排列 回溯法三部曲模板+树枝节点去重

    因为确定leecode测试用例:-10 <= nums[i] <= 10,所以使用固定数组来代替unordered_set<> 进行树枝节点去重操作,减少一定的开销,同时相对来 ...

  4. LeetCode Restore IP Addresses(回溯法)

    题意:给出一个由数字组成的字符串,求其能表示的ip地址列表 注意不能有前缀0,如010 思路:每次操作时,有两种情况,一种是添加点,一种是将其作为当前数的后序数. 在小数点的个数超过3时,递归退出. ...

  5. 146. Leetcode 51. N 皇后 (回溯算法-棋盘问题)

    class Solution:def solveNQueens(self, n: int) -> List[List[str]]:if not n: return []res = []board ...

  6. LeetCode 3. Longest Substring Without Repeating Characters-- c++,java,python解法

    题目地址: Given a string, find the length of the longest substring without repeating characters. Example ...

  7. Leetcode 37:解数独(超详细的解法!!!)

    编写一个程序,通过已填充的空格来解决数独问题. 一个数独的解法需遵循如下规则: 数字 1-9 在每一行只能出现一次. 数字 1-9 在每一列只能出现一次. 数字 1-9 在每一个以粗实线分隔的 3x3 ...

  8. LeetCode 37. Sudoku Solver--数独求解(回溯法)--Java 3ms,Python 80ms 解法

    题目地址: Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must sa ...

  9. LeetCode算法总结-回溯法与深度优先搜索

    转载自  LeetCode算法总结-回溯法与深度优先搜索 回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退 ...

最新文章

  1. 领跑交互新时代 蓦然认知助力传统产业智能化升级
  2. sh脚本学习之: sh脚本 、sed、awk
  3. 深入信号和槽(Signals and Slots in Depth)
  4. html5中的web storage的用法
  5. vm驱动程序版本不正确_微软 Win10 版本 2004 获得新版 Intel/Nvidia 显卡驱动程序
  6. 华为云HCIE认证有多难?考试内容是什么?
  7. 遭遇nat.exe,socks.exe,USP10.dll,BOSC.dll,kb080387.CNT,~ctwxw.txt等1
  8. python输入半径计算球的体积公式_编写程序:根据输入的球的半径,分别计算球的表面积、体积输出计算结果。...
  9. 产品流程、开发流程、测试流程、运维流程、售前流程改进建议
  10. VS2017--无法添加引用--提示“未能完成操作。不支持此接口”
  11. 聚观早报|百度3月16日发布文心一言;特斯拉被控维修和零部件垄断
  12. awesome php
  13. 使用“快剪辑”软件自定义修改视频尺寸
  14. IE浏览器默认主页被篡改,无法改回
  15. 鸿蒙 手游sdk 开发教程
  16. AIPNet: Image-to-Image Single Image Dehazing with Atmospheric Illumination Prior
  17. Qt处理传输协议数据时QByteArray添加多字节的使用案例
  18. python编程基础人邮版答案_《Python Web 编程》(人邮出版社)作业答案下载
  19. vim 退格键(backspace)
  20. 构建 PHP运行环境

热门文章

  1. RDKit | 基于分子指纹的相似性图
  2. Scanpy(二)对PBMC3k聚类
  3. 计算机科学与技术考,计算机科学与技术考研
  4. NC:中国药科郝海平和郑啸发现饮食-微生物互作缓解肠损伤
  5. STE:环境菌群代谢产物可预防炎症症状
  6. 1.4 微生物对人类社会的影响
  7. USEARCH11新功能简介
  8. python描述器 触发事件_Python面向对象 - 描述器
  9. R语言问题解决:Error: Discrete value supplied to continuous scale
  10. R语言plotly可视化:plotly可视化多个直方图、通过bingroup参数设置多个直方图使用相同的bins设置(Share bins between histograms)