八皇后問題

Problem

Place eight queens on an 8×8 chessboard so that no two queens attack each other.

Solution

// EightQueens.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

static int sTotalNumber = 0;

bool IsConflicted(vector<int> queensLoc, int nextRow, int expectedCol)
{
    // Dectect column conflict
    for (int j = 0; j < nextRow; ++j){
        if (queensLoc[j] == expectedCol){
            return true;
        }
    }

    // Detect dialognal conflict
    for (int j = 0; j < nextRow; ++j){
        if (abs(j - nextRow) == abs(queensLoc[j] - expectedCol)){
            return true;
        }
    }

    return false;
}

void LayNextQueen(vector<int> queensLoc, int row, int boardSize)
{
    if (row == boardSize){
        sTotalNumber++;
        cout << sTotalNumber << " --- ";
        copy(queensLoc.begin(), queensLoc.end(), ostream_iterator<int>(cout, " "));
        cout << endl;
    }

    for (int i = 0; i < boardSize; ++i){
        if (IsConflicted(queensLoc, row, i) == false){
            queensLoc.push_back(i);
            LayNextQueen(queensLoc, row + 1, boardSize);
            queensLoc.pop_back();
        }
    }
}

void EightQueens()
{
    vector<int> queensLoc;
    LayNextQueen(queensLoc, 0, 8);
}

int main(int argc, char* argv[])
{
    EightQueens();
    return 0;
}


Output

1 --- 0 4 7 5 2 6 1 3
2 --- 0 5 7 2 6 3 1 4
3 --- 0 6 3 5 7 1 4 2
4 --- 0 6 4 7 1 3 5 2
5 --- 1 3 5 7 2 0 6 4
6 --- 1 4 6 0 2 7 5 3
7 --- 1 4 6 3 0 7 5 2
8 --- 1 5 0 6 3 7 2 4
9 --- 1 5 7 2 0 3 6 4
10 --- 1 6 2 5 7 4 0 3
11 --- 1 6 4 7 0 3 5 2
12 --- 1 7 5 0 2 4 6 3
13 --- 2 0 6 4 7 1 3 5
14 --- 2 4 1 7 0 6 3 5
15 --- 2 4 1 7 5 3 6 0
16 --- 2 4 6 0 3 1 7 5
17 --- 2 4 7 3 0 6 1 5
18 --- 2 5 1 4 7 0 6 3
19 --- 2 5 1 6 0 3 7 4
20 --- 2 5 1 6 4 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 7 3 1 6 4
70 --- 5 2 0 7 4 1 3 6
71 --- 5 2 4 6 0 3 1 7
72 --- 5 2 4 7 0 3 1 6
73 --- 5 2 6 1 3 7 0 4
74 --- 5 2 6 1 7 4 0 3
75 --- 5 2 6 3 0 7 1 4
76 --- 5 3 0 4 7 1 6 2
77 --- 5 3 1 7 4 6 0 2
78 --- 5 3 6 0 2 4 1 7
79 --- 5 3 6 0 7 1 4 2
80 --- 5 7 1 3 0 6 4 2
81 --- 6 0 2 7 5 3 1 4
82 --- 6 1 3 0 7 4 2 5
83 --- 6 1 5 2 0 3 7 4
84 --- 6 2 0 5 7 4 1 3
85 --- 6 2 7 1 4 0 5 3
86 --- 6 3 1 4 7 0 2 5
87 --- 6 3 1 7 5 0 2 4
88 --- 6 4 2 0 5 7 1 3
89 --- 7 1 3 0 6 4 2 5
90 --- 7 1 4 2 0 6 3 5
91 --- 7 2 0 5 1 4 6 3
92 --- 7 3 0 2 5 1 6 4
Press any key to continue . . .



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