קוד:
case 5:
{
puts ("enter the size of the board");
scanf ("%d", &size);
/* Allocating memory for Two-dimensional arrays */
board=(int**)malloc(size*sizeof(int*));
allocating(board,size,0);
/* Initialization */
initialize(board,size,0,0);
puts ("enter the number of the requested solution");
scanf ("%d", &solution);
n_queens(board,size,solution);
free(board);
main(); //return to the main
break;
}
default: main();
קוד:
void allocating(int** arr, int size, int i)
{
/* allocate memory for the entire array */
if (i==size)
return;
*(arr+i)=(int*)malloc(size*sizeof(int));
i++;
allocating(arr,size,i);
}
פונקציה שמאתחלת מערך דו ממדי ל0
void initialize(int** board, int size, int i, int j)
{
if (j==size) // move one line down
{
j=0;
i++;
}
if (i==size) //out of the array
return;
board[i][j]=0;
// initialize
j++;
initialize(board,size,i,j);
}
void n_queens (int** board, int size, int solution_num) { solution(board,size,solution_num,0,0);
PrintChessBoard(board,size,0,0);
printf ("\n"); }
לפונקציה הזאת זה לא נכנס במצב RELEASE
int isLegit (int **board, int n, int x, int y, int iDir, int jDir) {
if(x<0 || x==n || y<0 || y==n) // out of the board
return 1;
else if (board[x][y]==1) // met queen , not legal move
return 0;
x+=iDir;
y+=jDir;
isLegit(board,n,x,y,iDir,jDir);
}
int solution (int** board, int size, int solution_num, int col, int i) {
if (col==size) return solution_num-1;
for (i=0;i<size;i++) { /* now we're checking 3 different directions, and if we receive 1 in all the three calls we can put our queen here !!!!! */
if (isLegit(board,size,i,col,-1,-1)&& isLegit(board,size,i,col,0,-1)&& isLegit(board,size,i,col,1,-1))
{
board[i][col]=1;
solution_num=solution(board,size,solution_num,col+ 1,0); // promote col + 1 check the new column
if (!solution_num) // checked already all possible solutions till the user's choice
return 0;
else board[i][col]=0;
}
}
return solution_num;
}
void PrintChessBoard (int **board, int size, int row, int col)
{ /* Print The user's solution chocie Chess board */
if (col==size) {
col=0;
row++;
if (row==size) return;
printf ("\n"); }
printf ("%d ", board[row][col]);
PrintChessBoard(board,size,row,col+1); }