Created
February 6, 2012 15:48
-
-
Save ageekymonk/1752774 to your computer and use it in GitHub Desktop.
Solution For Eight Queen Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <string> | |
#include <algorithm> | |
using namespace std; | |
void printChess(vector<vector<int> > &board) | |
{ | |
static int i = 1; | |
cout << "****************************"<< i++ << "***************************************" << endl; | |
for (int i=0; i<8; i++) | |
{ | |
for (int j=0; j<8; j++) | |
{ | |
cout << board[i][j] << "\t"; | |
} | |
cout << endl; | |
} | |
} | |
void placeQueen(vector<vector<int> > &board, int row) | |
{ | |
int mov_row[] = { 0,1,0,-1,-1,-1,1,1}; | |
int mov_col[] = { 1,0,-1,0,1,-1,-1,1}; | |
if (row == 8) | |
{ | |
printChess(board); | |
return; | |
} | |
for(int i=0; i<8; i++) | |
{ | |
int flag_ignore = 0; | |
int k=0; | |
for(int j=0; j<8; j++) | |
{ | |
int temp_row = row; | |
int temp_col = i; | |
while ((temp_row >=0) && (temp_row<8) && (temp_col>=0) && (temp_col<8)) | |
{ | |
if (board[temp_row][temp_col] == 8) | |
{ | |
flag_ignore=1; | |
break; | |
} | |
temp_row += mov_row[j]; | |
temp_col += mov_col[j]; | |
} | |
if (flag_ignore) | |
break; | |
} | |
if (!flag_ignore) | |
{ | |
board[row][i] = 8; | |
//cout << "Placed queen at " << row << "," << i << endl; | |
placeQueen(board, row+1); | |
board[row][i] = 1; | |
} | |
} | |
} | |
int main() | |
{ | |
vector<vector<int> > board(8,vector<int>(8,1)); | |
placeQueen(board,0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment