Last active
August 22, 2017 16:47
-
-
Save roychowdhuryrohit-dev/38583cd493e669c3d07de278cbc63745 to your computer and use it in GitHub Desktop.
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 <stdio.h> | |
#include <math.h> | |
#include <stdlib.h> | |
#define X 99 | |
// To reset the board and remove queens. | |
void reset(int *board, int dim) { | |
int i; | |
for(i = 0;i<dim;i++) { | |
board[i] = X; | |
} | |
} | |
void printBoard(int *board, int dim) { | |
int i, j; | |
for(i = 0;i<dim;i++) { | |
for(j = 0;j<dim;j++) { | |
if(board[i] == j) { | |
printf("Q "); | |
} | |
else { | |
printf("X "); | |
} | |
} | |
puts(""); | |
} | |
puts(""); | |
} | |
int *initBoard(int dim) { | |
int i, *board; | |
board = (int *) malloc(dim*sizeof(int)); | |
reset(board, dim); | |
return board; | |
} | |
// To check conflicts in columns and diagonals. | |
int checkConflict(int *board, int dim, int curRow, int curCol) { | |
int i; | |
for(i = 0;i<curCol;i++) { | |
if(board[i] == curRow) { | |
return 1; | |
} | |
else if(abs(board[i] - curRow) == abs(i - curCol)) { | |
return 1; | |
} | |
} | |
return 0; | |
} | |
int backtrack(int *board, int dim, int curCol) { | |
int i, found = 0; | |
// If solution is found. | |
if(curCol == dim) { | |
printBoard(board, dim); | |
return 1; | |
} | |
for(i = 0;i<dim;) { | |
// Check if solution is possible in ith row. | |
if(checkConflict(board, dim, i, curCol)) { | |
i++; | |
continue; | |
} | |
else { | |
board[curCol] = i; | |
// Check solution in next column. | |
if(backtrack(board, dim, curCol + 1)) { | |
found = 1; | |
} | |
} | |
if(curCol == 0) { | |
reset(board, dim); | |
} | |
i++; | |
} | |
return found; | |
} | |
int main() { | |
int dim, *board, i; | |
printf("Enter the dim : "); | |
scanf("%d", &dim); | |
board = initBoard(dim); | |
if(!backtrack(board, dim, 0)) { | |
puts("No solution found !"); | |
} | |
free(board); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment