LeetCode No.51 N-Queens

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

===================================================================

題目鏈接:https://leetcode.com/problems/n-queens/

題目大意:N皇后問題,求出所有滿足N皇后的解法。

思路:深度搜索,寬度搜索或者回溯。

參考代碼:

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector < vector <string> > ans ;
        if ( n == 0 )
        {
            vector <string> temp ;
            ans.push_back ( temp ) ;
            return ans ;
        }
        for ( int i = 0 ; i < n ; i ++ )
        {
            vector < pair <int,int> > v ;
            v.push_back ( make_pair ( 0 , i ) ) ;
            queue < vector < pair <int,int> > > q ;
            q.push ( v ) ;
            while ( ! q.empty() )
            {
                v = q.front() ;
                q.pop() ;
                if ( v.size() == n )
                {
                    ans.push_back ( buildBoard ( n , v ) ) ;
                    continue ;
                }
                int index = v.back().first + 1 ;
                for ( int j = 0 ; j < n ; j ++ )
                {
                    if ( isValid ( n , v , index , j ) ) 
                    {
                        vector < pair <int,int> > temp = v ;
                        temp.push_back ( make_pair ( index , j ) ) ;
                        if ( index == n - 1 )
                            ans.push_back ( buildBoard ( n , temp ) ) ;
                        else
                            q.push ( temp ) ;
                    }
                }
            }
        }
        return ans ;
    }
private :
    bool isValid ( int n , const vector < pair <int,int> >& v , int x , int y )
    {
        for ( int i = 0 ; i < v.size() ; i ++ )
        {
            if ( x == v[i].first || y == v[i].second || x - v[i].first == y - v[i].second || x - v[i].first == v[i].second - y )
                return false ;
        }
        return true ;
    }
    vector <string> buildBoard ( int n , const vector < pair <int,int> >& v )
    {
        string s ( n , '.' ) ;
        vector <string> b ( n , s ) ;
        for ( int i = 0 ; i < v.size() ; i ++ )
        {
            b[v[i].first][v[i].second] = 'Q' ;
        }
        return b ;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章