Skip to content

Instantly share code, notes, and snippets.

@henrybear327
Created May 1, 2017 11:09
Show Gist options
  • Save henrybear327/5a003445c1b1e7ba7bc51eb746ab0423 to your computer and use it in GitHub Desktop.
Save henrybear327/5a003445c1b1e7ba7bc51eb746ab0423 to your computer and use it in GitHub Desktop.
nqueen.cpp
#include <bits/stdc++.h>
using namespace std;
#define N 8
bool seen[N][N];
bool row[N];
int ans = 0;
void dfs(int depth)
{
if(depth == N) {
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
printf("%d%c", seen[i][j], j == N - 1 ? '\n' : ' ');
}
}
printf("\n");
ans++;
return;
}
for(int i = 0; i < N; i++) {
bool error = false;
if(row[i] == 0) {
for(int j = 1; j <= depth; j++) {
if(i - j >= 0 && seen[depth - j][i - j] == 1) {
error = true;
break;
}
if(i + j < N && seen[depth - j][i + j] == 1) {
error = true;
break;
}
}
if(error)
continue;
seen[depth][i] = 1;
row[i] = 1;
dfs(depth + 1);
seen[depth][i] = 0;
row[i] = 0;
}
}
}
int main()
{
memset(seen, false, sizeof(seen));
memset(row, false, sizeof(row));
dfs(0);
printf("total %d\n", ans);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment