现在看来,n皇后问题也不过如此了。。。我的是C++版本。
queens.h// Queens.h
const int max_board = 30;
class Queens{
public:
Queens(int size);
bool is_solved() const;
void print() const;
bool unguarded(int col) const;
void insert(int col);
void remove(int col);
int board_size; //Dimension of board = maximum number of queens
private:
int _count; //Current number of queens = first unoccupied row
bool col_free[max_board];
bool up_free[2*max_board-1];
bool down_free[2*max_board-1];
int queen_in_row[max_board]; // column number of queen in each row
};
Queens::Queens(int size)
: board_size(size), _count(0)
{
for(int i = 0; i < board_size; ++i) col_free[i] = true;
for(int j = 0; j < (2*max_board-1); ++j) up_free[j] = true;
for(int k = 0; k < (2*max_board-1); ++k) down_free[k] = true;
}
bool Queens::is_solved() const
{
return _count == board_size;
}
void Queens::insert(int col)
{
queen_in_row[_count] = col;
col_free[col] = false;
up_free[_count+col] = false;
down_free[_count-col+board_size-1] = false;
_count++;
}
void Queens::remove(int col)
{
_count--;
queen_in_row[_count] = 0;
col_free[col] = true;
up_free[_count+col] = true;
down_free[_count-col+board_size-1] = true;
}
void Queens::print() const
{
for(int row = 0; row < board_size; ++row)
{
std::cout << "|";
for(int col = 0; col < board_size; ++col)
{
if(queen_in_row[row] == col) std::cout << "Q|";
else std::cout << " |";
}
std::cout << "\n";
}
std::cout << "*******************************\n";
}
bool Queens::unguarded(int col) const
{
return col_free[col]
&& up_free[_count+col]
&& down_free[_count-col+board_size-1];
}
main.cpp#include <iostream>
#include "queens.h"
void solve_from(Queens &config)
{
if(config.is_solved()) config.print();
else
for(int col = 0; col < config.board_size; ++col)
if(config.unguarded(col))
{
config.insert(col);
solve_from(config); //Recursively continue to add queens
config.remove(col);
}
}
int main()
{
int board_size;
// print_information();
std::cout << "What is the size of the board?" << std::flush;
std::cin >> board_size;
if(board_size < 0 || board_size > max_board)
std::cout << "The number must between 0 and " << max_board << std::endl;
else{
Queens config(board_size); //Initialize empty configuration
solve_from(config); //Find all solutions extending configuration
}
}
|