Created
November 22, 2018 02:37
-
-
Save hsinewu/61d174d49d569cab1bb9c1566448cec7 to your computer and use it in GitHub Desktop.
eight queen backtracking c++
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 <bits/stdc++> | |
#include <cstdio> | |
#include <cstdlib> | |
// using namespace std; | |
#define QUEEN 8 | |
int cnt; | |
void printGrid(int grid[][QUEEN]) { | |
for(int i=0; i<QUEEN; i++) { | |
for(int j=0; j<QUEEN; j++) { | |
printf("%d ", grid[i][j]); | |
} | |
putchar('\n'); | |
} | |
putchar('\n'); | |
} | |
void backtrack(int grid[][QUEEN], int col[], int dia[], int dxa[], int i) { | |
if(i == QUEEN) { | |
printGrid(grid); | |
cnt++; | |
return; | |
} | |
for(int j=0; j<QUEEN; j++) { | |
if(col[j] + dia[i-j] + dxa[i+j]) continue; | |
dxa[i+j] = dia[i-j] = col[j] = grid[i][j] = 1; | |
backtrack(grid, col, dia, dxa, i+1); | |
dxa[i+j] = dia[i-j] = col[j] = grid[i][j] = 0; | |
} | |
} | |
int main() { | |
int grid[QUEEN][QUEEN] = {}, col[QUEEN] = {}, dia[2*QUEEN] = {}, dxa[2*QUEEN] = {}; | |
backtrack(grid, col, dia+QUEEN, dxa, 0); | |
printf("%d\n", cnt); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment