zoukankan      html  css  js  c++  java
  • 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;
        }
    };


  • 相关阅读:
    5月16日 AJAX
    5月13日 Jquery基础
    5月13日 PDO封装
    会话控制练习
    文件上传
    会话控制
    注册审核
    练习
    三级联动
    AJAX之XML
  • 原文地址:https://www.cnblogs.com/hrnn/p/13402869.html
Copyright © 2011-2022 走看看