LeetCode:N-Queens I II(n皇后問題)

N-Queenshtml

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:spa

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

 

算法1.net

這種棋盤類的題目通常是回溯法, 依次放置每行的皇后。在放置的時候,要保持當前的狀態爲合法,即當前放置位置的同一行、同一列、兩條對角線上都不存在皇后。code

class Solution {
private:
    vector<vector<string> > res;
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<string>cur(n, string(n,'.'));
        helper(cur, 0);
        return res;
    }
    void helper(vector<string> &cur, int row)
    {
        if(row == cur.size())
        {
            res.push_back(cur);
            return;
        }
        for(int col = 0; col < cur.size(); col++)
            if(isValid(cur, row, col))
            {
                cur[row][col] = 'Q';
                helper(cur, row+1);
                cur[row][col] = '.';
            }
    }
    
    //判斷在cur[row][col]位置放一個皇后,是不是合法的狀態
    //已經保證了每行一個皇后,只須要判斷列是否合法以及對角線是否合法。
    bool isValid(vector<string> &cur, 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 < cur.size(); i--,j++)
            if(cur[i][j] == 'Q')return false;
        return true;
    }
};

 

算法2htm

上述判斷狀態是否合法的函數仍是略複雜,其實只須要用一個一位數組來存放當前皇后的狀態。假設數組爲int state[n], state[i]表示第 i 行皇后所在的列。那麼在新的一行 k 放置一個皇后後:blog

  • 判斷列是否衝突,只須要看state數組中state[0…k-1] 是否有和state[k]相等;
  • 判斷對角線是否衝突:若是兩個皇后在同一對角線,那麼|row1-row2| = |column1 - column2|,(row1,column1),(row2,column2)分別爲衝突的兩個皇后的位置
class Solution {
private:
    vector<vector<string> > res;
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<int> state(n, -1);
        helper(state, 0);
        return res;
    }
    void helper(vector<int> &state, int row)
    {//放置第row行的皇后
        int n = state.size();
        if(row == n)
        {
            vector<string>tmpres(n, string(n,'.'));
            for(int i = 0; i < n; i++)
                tmpres[i][state[i]] = 'Q';
            res.push_back(tmpres);
            return;
        }
        for(int col = 0; col < n; col++)
            if(isValid(state, row, col))
            {
                state[row] = col;
                helper(state, row+1);
                state[row] = -1;;
            }
    }
    
    //判斷在row行col列位置放一個皇后,是不是合法的狀態
    //已經保證了每行一個皇后,只須要判斷列是否合法以及對角線是否合法。
    bool isValid(vector<int> &state, int row, int col)
    {
        for(int i = 0; i < row; i++)//只須要判斷row前面的行,由於後面的行尚未放置
            if(state[i] == col || abs(row - i) == abs(col - state[i]))
                return false;
        return true;
    }
};

 

算法3:(算法2的非遞歸版)遞歸

class Solution {
private:
    vector<vector<string> > res;
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<int> state(n, -1);
        for(int row = 0, col; ;)
        {
            for(col = state[row] + 1; col < n; col++)//從上一次放置的位置後面開始放置
            {
                if(isValid(state, row, col))
                {
                    state[row] = col;
                    if(row == n-1)//找到了一個解,繼續試探下一列
                    {
                        vector<string>tmpres(n, string(n,'.'));
                        for(int i = 0; i < n; i++)
                            tmpres[i][state[i]] = 'Q';
                        res.push_back(tmpres);
                    }
                    else {row++; break;}//當前狀態合法,去放置下一行的皇后
                }
            }
            if(col == n)//當前行的全部位置都嘗試過,回溯到上一行
            {
                if(row == 0)break;//全部狀態嘗試完畢,退出
                state[row] = -1;//回溯前清除當前行的狀態
                row--;
            }
        }
        return res;
    }
    
    //判斷在row行col列位置放一個皇后,是不是合法的狀態
    //已經保證了每行一個皇后,只須要判斷列是否合法以及對角線是否合法。
    bool isValid(vector<int> &state, int row, int col)
    {
        for(int i = 0; i < row; i++)//只須要判斷row前面的行,由於後面的行尚未放置
            if(state[i] == col || abs(row - i) == abs(col - state[i]))
                return false;
        return true;
    }
};

 

算法4(解釋在後面)這應該是最高效的算法了

class Solution {
private:
    vector<vector<string> > res;
    int upperlim;
public:
    vector<vector<string> > solveNQueens(int n) {
        upperlim = (1 << n) - 1;//低n位所有置1
        vector<string> cur(n, string(n, '.'));
        helper(0,0,0,cur,0);
        return res;
    }
    
    void helper(const int row, const int ld, const int rd, vector<string>&cur, const int index)
    {
    	int pos, p;
    	if ( row != upperlim )
    	{
    		pos = upperlim & (~(row | ld | rd ));//pos中二進制爲1的位,表示能夠在當前行的對應列放皇后
    		//和upperlim與運算,主要是ld在上一層是經過左移位獲得的,它的高位可能有無效的1存在,這樣會清除ld高位無效的1
    		while ( pos )
    		{
    			p = pos & (~pos + 1);//獲取pos最右邊的1,例如pos = 010110,則p = 000010
    			pos = pos - p;//pos最右邊的1清0
    			setQueen(cur, index, p, 'Q');//在當前行,p中1對應的列放置皇后
    			helper(row | p, (ld | p) << 1, (rd | p) >> 1, cur, index+1);//設置下一行
    			setQueen(cur, index, p, '.');
    		}
    	}
    	else//找到一個解
            res.push_back(cur);
    }
    
    //第row行,第loc1(p)列的位置放置一個queen或者清空queen,loc1(p)表示p中二進制1的位置
    void setQueen(vector<string>&cur, const int row, int p, char val)
    {
        int col = 0;
        while(!(p & 1))
        {
            p >>= 1;
            col++;
        }
        cur[row][col] = val;
    }
};

 

這個算法主要參考博客N皇后問題的兩個最高效的算法,主要看helper函數,參數row、ld、rd分別表示在列和兩個對角線方向的限制條件下,當前行的哪些地方不能放置皇后。以下圖

image 

前三行放置了皇后,他們對第3行(行從0開始)的影響以下:                               本文地址

(1)列限制條件下,第3行的0、二、4列(紫色線和第3行的交點)不能放皇后,所以row = 101010

(2)左對角線限制條件下,第3行的0、3列(藍色線和第3行的交點)不能放皇后,所以ld = 100100

(3)右對角線限制條件下,第3行的三、四、5列(綠色線和第3行的交點)不能放皇后,所以rd = 000111

 

~(row | ld | rd) = 010000,即第三行只有第1列能放置皇后。

在3行1列這個位置放上皇后,row,ld,rd對下一行的影響爲:

row的第一位置1,變爲111010

ld的第一位置1,而且向左移1位(由於左對角線對行的影響是依次向左傾斜的),變爲101000

rd的第一位置1,而且向右移1位(由於右對角線對行的影響是依次向右傾斜的),變爲001011

 

第4行狀態以下圖

image 

 


N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

 

這一題就是上一題的簡化版了,咱們只針對上面的算法2來求解這一題

class Solution {
private:
    int res;
public:
    int totalNQueens(int n) {
        vector<int> state(n, -1);
        res = 0;
        helper(state, 0);
        return res;
    }
    void helper(vector<int> &state, int row)
    {//放置第row行的皇后
        int n = state.size();
        if(row == n)
        {
            res++;
            return;
        }
        for(int col = 0; col < n; col++)
            if(isValid(state, row, col))
            {
                state[row] = col;
                helper(state, row+1);
                state[row] = -1;;
            }
    }
    
    //判斷在row行col列位置放一個皇后,是不是合法的狀態
    //已經保證了每行一個皇后,只須要判斷列是否合法以及對角線是否合法。
    bool isValid(vector<int> &state, int row, int col)
    {
        for(int i = 0; i < row; i++)//只須要判斷row前面的行,由於後面的行尚未放置
            if(state[i] == col || abs(row - i) == abs(col - state[i]))
                return false;
        return true;
    }

};

 

【版權聲明】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3801621.html

相關文章
相關標籤/搜索