A better approach is to simply keep track of free rows, columns and
diagonals (both). One of the [rows,columns] gets handled by the
obvious loop (you don't try placing two queens on one of those). For
simplicity I'll assume columns. The others just need a bitmap for
each row or diagonal. There are 8* rows, and 15* (#rows*2-1)
diagonals in each of two directions.
Assume the columns are numbered 0-7, right-to-left, the rows 0-7,
top-to-bottom, and the diagonals (D1 and D2) are numbered 0-14,
top-to-bottom (D1 represents to upper-left to lower-right diagonals,
D2 the lower-left to upper-right). Assume you're working in column C,
and are attempting to place in queen in row R. You can just check the
row bitmap to check for a conflict on a row. You can trivially
compute the two diagonals the prospective queen is on (D1=(7-C)+R and
D2=C+R), and then just those two bits in each bitmap to check for
conflicts on the diagonals.
If you find a possible location, mark the appropriate row and (both)
diagonal bits, and move on to the next column. As you backtrack,
unmark the R/D1/D2 bits. Total storage is linear in the size of a
side of the board.
So you end up with something like:
Column[0..7] =0
Rbitmap[0..7]=0
D1bitmap[0..14]=0
D2bitmap[0..14]=0
main()
PlaceNextColumn(0)
PlaceNextColumn(C)
for(R=0..7)
Column[C]=R
Try(R,C)
Try(R,C)
D1=(7-C)+R
D2=C+R
if (Rbitmap[R]) return //conflict
if (D1bitmap[D1]) return //conflict
if (D2bitmap[D2]) return //conflict
// (no conflict)
Rbitmap[R]=1
D1bitmap[D1]=1
D2bitmap[D2]=1
if(C==7)
OutputSolution()
else
PlaceNextColumn(C+1)
Rbitmap[R]=0
D1bitmap[D1]=0
D2bitmap[D2]=0
OutputSolution()
printf("\nSolution: ")
for(C=0..7)
printf("Queen in column %i, on row %i ", C, Column[C])
*Assuming a standard chessboard - the approach generalizes to other
sizes, and rectangular boards