Created
August 24, 2013 22:56
-
-
Save ygabo/6330877 to your computer and use it in GitHub Desktop.
Write an algorithm to prim 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.
This file contains hidden or 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 <string> | |
#include <vector> | |
#include <math.h> | |
#include <map> | |
#include <fstream> | |
#include < ctime > | |
#include <algorithm> | |
#include <vector> | |
#include <iostream> | |
#include <set> | |
using namespace std; | |
bool valid( vector<vector<int>> &b, int x, int y){ | |
int w = b.size(); | |
int h = b[0].size(); | |
// column and row | |
for( int i = 0; i < w; i++){ | |
if( b[x][i] ) return false; | |
if( b[i][y] ) return false; | |
} | |
// check diagonals | |
int tx = x+1, ty = y+1; | |
while( tx < w && ty < h ){ | |
if( b[tx++][ty++] ) return false; | |
} | |
tx = x-1, ty = y-1; | |
while( tx >= 0 && ty >= 0 ){ | |
if( b[tx--][ty--] ) return false; | |
} | |
tx = x+1, ty = y-1; | |
while( tx < w && ty >= 0 ){ | |
if( b[tx++][ty--] ) return false; | |
} | |
tx = x-1, ty = y+1; | |
while( tx > 0 && ty < h ){ | |
if( b[tx--][ty++] ) return false; | |
} | |
return true; | |
} | |
bool placeQ( vector<vector<int>>& b, int col, set<vector<vector<int>>> &ans){ | |
if ( col >= b[0].size() ) | |
return true; | |
for( int i = 0; i < b.size(); i++){ | |
if( valid(b, i, col) ){ | |
b[i][col] = 1; | |
if( !placeQ(b, col+1, ans) ) | |
b[i][col] = 0; | |
else{ | |
if( col == 0 ){ | |
ans.insert(b); | |
std::fill(b.begin(),b.end(),vector<int>(b.size())); | |
} | |
else | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
int main(){ | |
int n = 8; | |
vector<vector<int>> b(n, vector<int>(n,0)); | |
set<vector<vector<int>>> ans; | |
placeQ(b, 0, ans); | |
for( auto f = ans.begin(); f != ans.end(); ++f){ | |
for( auto i = f->begin(); i != f->end(); ++i){ | |
for( auto j = i->begin(); j != i->end(); ++j){ | |
cout << *j << " "; | |
} | |
cout << endl; | |
} | |
cout << endl << endl; | |
} | |
cout << endl << "Done." <<endl; | |
cin.get(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you explain the intuition for this part:
Are you essentially setting the checks for the rows and columns to false?