• leetcode99:n-queens


    题目描述

    N皇后问题是把N个皇后放在一个N×N棋盘上,使皇后之间不会互相攻击。

    给出一个整数n,返回n皇后问题的所有摆放方案
    例如:
    4皇后问题有两种摆放方案
    [".Q..",  // 解法 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // 解法 2
      "Q...",
      "...Q",
      ".Q.."]
    ]
    


    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..",  // 解法 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // 解法 2
      "Q...",
      "...Q",
      ".Q.."]
    class Solution {
    public:
        vector<vector<string> > solveNQueens(int n) {
            vector <vector<string>> res;
            vector<string> cur(n,string(n,'.'));
            dfs(res,cur,n,0);
            return res;
        }
        
        void dfs(vector <vector<string>> &res,vector <string> &cur,int &n,int row){
            if (row==n){
                res.push_back(cur);
                return ;
            }
            
            for (int j=0;j<n;j++){
                if (isValid (cur,n,row,j)){
                    cur[row][j]='Q';
                    dfs(res,cur,n,row+1);
                    cur[row][j]='.';
                }
            }
        }
        
        bool isValid(vector<string> &cur,int &n ,int row,int col){
            for (int i=0;i<row;i++){
                if (cur[i][col]=='Q'){
                    return false;
                }
            }
            
            for (int i=row-1,j=col-1;i>=0 && j>=0;i--,j--){
                if (cur[i][j]=='Q'){
                    return false;
                }
            }
            
            for (int i=row-1,j=col+1;i>=0 && j<n;i--,j++){
                if (cur[i][j]=='Q'){
                    return false;
                }
                    
            }
        
        return true;
        }
    };


  • 相关阅读:
    发卡构型高分子的跨膜传输
    《一个数学家的叹息》读后
    匀速拉地毯最少需要多大的力
    桥环形高分子的标度理论——链滴图像
    试验1
    自定义控件EditText
    自定义控件TextView
    HTTP的应用httpclient 和线程
    http的应用httpurlconnection--------1
    学习笔记—Fragement +Actionbar
  • 原文地址:https://www.cnblogs.com/hrnn/p/13402869.html
Copyright © 2020-2023  润新知