Skip to content

Instantly share code, notes, and snippets.

@mtao
Last active November 2, 2017 04:56
Show Gist options
  • Save mtao/fd6ed0d1a37ce8b743f0be4a34b230da to your computer and use it in GitHub Desktop.
Save mtao/fd6ed0d1a37ce8b743f0be4a34b230da to your computer and use it in GitHub Desktop.
nqueens solver i wound up writing on the side while guiding someone thoruhg c multidimensional arrays
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <iterator>
#include <iostream>
bool is_nqueens(const std::vector<int>& pos) {
//assume row and col safety
std::set<int> diag1;
std::set<int> diag2;
for(int i = 0; i < pos.size(); ++i) {
diag1.insert(pos[i]-i);
diag2.insert(pos[i]+i);
}
return (diag1.size() == pos.size()) && (diag2.size() == pos.size());
}
void print(const std::vector<int>& pos) {
for(int i = 0; i < pos.size(); ++i) {
for(int j = 0; j < pos[i]; ++j) {
std::cout << ".";
}
std::cout << "o";
for(int j = pos[i]+1; j < pos.size(); ++j) {
std::cout << ".";
}
std::cout << std::endl;
}
for(int j = 0; j < pos.size(); ++j) {
std::cout << "=";
}
std::cout << std::endl;
}
int main(int argc, char * argv[]) {
int size = 8;
if(argc == 2) {
size = std::atoi(argv[1]);
}
std::vector<int> pos(size);
std::iota(pos.begin(),pos.end(),0);
do {
if(is_nqueens(pos)) {
print(pos);
}
std::next_permutation(pos.begin(),pos.end());
} while(!std::is_sorted(pos.begin(),pos.end()));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment