Skip to content

Instantly share code, notes, and snippets.

@vivekannan
Last active August 29, 2015 14:03
Show Gist options
  • Save vivekannan/e0fb03604cde20fc58fc to your computer and use it in GitHub Desktop.
Save vivekannan/e0fb03604cde20fc58fc to your computer and use it in GitHub Desktop.
A quick N-Queens solver.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#define QUEENS 8
using namespace std;
class Board {
private:
char board[QUEENS][QUEENS];
int placed;
int safe(int x, int y);
int filled();
void print_board();
void place_queen(int x, int y);
void clear();
public:
Board();
int run();
};
Board::Board() {
int i, j;
for(i = 0; i < QUEENS; i++)
for(j = 0; j < QUEENS; j++)
board[i][j] = '.';
placed = 0;
run();
}
int Board::safe(int x, int y) {
return board[x][y] == '.';
}
int Board::filled() {
int i, j;
for(i = 0; i < QUEENS; i++)
for(j = 0; j < QUEENS; j++)
if(board[i][j] == '.')
return 0;
return 1;
}
void Board::print_board() {
int i, j;
for(i = 0; i < QUEENS; i++) {
for(j = 0; j < QUEENS; j++)
cout << board[i][j] << " ";
cout << "\n";
}
}
void Board::place_queen(int x, int y) {
int i, j;
placed++;
for(i = 0; i < QUEENS; i++)
for(j = 0; j < QUEENS; j++) {
if(i == x && j == y)
board[i][j] = 'Q';
else if(x == i || y == j || i + j == x + y || abs(i - x) == abs(j - y))
board[i][j] = '*';
}
}
void Board::clear() {
int i, j;
for(i = 0; i < QUEENS; i++)
for(j = 0; j < QUEENS; j++)
board[i][j] = '.';
placed = 0;
}
int Board::run() {
srand(unsigned(time(NULL)));
int a, b;
while(1) {
while(!filled()) {
a = rand() % QUEENS;
b = rand() % QUEENS;
if(safe(a, b))
place_queen(a, b);
}
if(placed == QUEENS) {
print_board();
return 1;
}
clear();
}
}
int main() {
Board b;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment