Eight Queen Puzzle
/***
9.9
Write an algorithm to print all ways of arranging eight queens on an 8X8 chess
board so that none of them share the same row, column or diagonal. In this case,
"diagonal" means all diagonals, not just the two that bisect the board.
M*N
row[n] = col
***/
#include<iostream>
#include<vector>
#include<climits>
#include <cmath>
using namespace std;
#define ROW 8
#define COL 8
bool isvalid(vector<int> row, int r, int col) {
for(int i = 0; i<r; i++) {
if(col == row[i]) return false;
if(abs(row[i] - col) == r-i) return false;
}
return true;
}
void placequeen(vector<int> row, int r, vector<vector<int>> *ways) {
if(r == ROW) {
ways->push_back(row);
}
else {
for(int i = 0; i<COL; i++) {
if(isvalid(row, r, i)) {
row[r] = i;
placequeen(row, r+1, ways);
}
}
}
}
void main() {
vector<vector<int>> placeway;
vector<int> row;
for(int i = 0; i<ROW; i++) row.push_back(INT_MAX);
placequeen(row, 0, &placeway);
for(int i = 0; i < placeway.size(); i++) {
for(int j = 0; j < ROW; j++)
cout<<placeway[i][j]<<" ";
cout<<endl;
}
}
Comments
Post a Comment