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

轉載來自http://www.cnblogs.com/TenosDoIt/p/3801621.html博客園

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

 

算法1

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
    }
};

 

算法2

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

  • 判斷列是否衝突,只需要看state數組中state[0…k-1] 是否有和state[k]相等;
  • 判斷對角線是否衝突:如果兩個皇后在同一對角線,那麼|row1-row2| = |column1 - column2|,(row1,column1),(row2,column2)分別爲衝突的兩個皇后的位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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的非遞歸版)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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(解釋在後面)這應該是最高效的算法了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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;
    }
};


詳細註釋的解法如下
class Solution {
private:
    vector<vector<string>> res;
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<int> state(n, -1);//每行皇后的位置,state[i]是第i行皇后的位置在state[i] 列數
        helper(state, 0);
        return res;
    }
    void helper(vector<int> &state, int row)
    {//放置第row行的皇后
        int n = state.size();
        if(row == n) //所有行數已確定了皇后位置,n是矩陣的行數
        {
            vector<string>tmpres(n, string(n,'.'));
            for(int i = 0; i < n; i++)
                tmpres[i][state[i]] = 'Q';
            res.push_back(tmpres);//形象顯示出n皇后的位置結果
            return;//此處結束N皇后問題
        }
        for(int col = 0; col < n; col++)//確定每一行的皇后列數,通過遍歷列數來判斷位置是否有效
            if(isValid(state, row, col))
            {
                state[row] = col;//第row行的皇后在第col列位置上
                helper(state, row+1);//row+1,皇后繼續擺放到第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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章