Here I am trying to solve the infamous eight queens problem. When I finally thought I got it, a segmentation fault hits me out of nowhere. The code:
#include<unistd.h>
#include<stdio.h>
int isLastBoard(int *chessBoard){
for(int i = 0 ; i < 8 ; ++i){
if(chessBoard[i] != 7)return 0;
}
return 1;
}
int isFit(int *tab){
for(int i = 1; i < 8 ; ++i){
for(int j = 0 ; j < i ; ++j){
if(tab[i] == tab[j] || tab[i] == tab[j] + i -j|| tab[i] == tab[j] - i + j)return 0;
}
}
return 1;
}
int *getNextBoard(int chessBoard[], int n){
if(n == 0 && chessBoard[n] == 7)return NULL;
chessBoard[n] = (chessBoard[n] + 1) % 8;
if(chessBoard[n]==0)return getNextBoard(chessBoard,n-1);
return chessBoard;
}
int countPossibilities(int *chessBoard,int n){
for(int i = 0 ; i <8 ; ++i){
printf("%d",chessBoard[i]);
}
printf(" %d\n",n);
if(isLastBoard(chessBoard))return n;
if(isFit(chessBoard))return countPossibilities(getNextBoard(chessBoard,7),n+1);
return countPossibilities(getNextBoard(chessBoard,7), n);
}
int ft_eight_queens_puzzle(void){
int chessBoard[8] = {0,0,0,0,0,0,0,0};
return countPossibilities(chessBoard, 0);
}
int main(void){
printf("%d", ft_eight_queens_puzzle());
return 0;
}
The program executes and counts up to the board set 00377455, and then gives a segmentation fault. Any help would be appreciated.
I have tried to use a table instead of an int so that i don't surpass the int size limit, and because it's easier. I tried to check if any of my fuctions aren't working, but all seems good.
I use gcc to compile and visual studio code to debug.
~edit:
I would also appreciate any comments or criticisms on my code that would help to improve it.