#include "stdafx.h" #include int pairs(char *brd[],int r,int c) { int attacks = 0; int tr; int tc; for(int cc=0;cc<8;cc++) attacks += ((cc!=c)&&(brd[r][cc]=='Q'))?1:0; for (int k=-7;k=0)&&(tr=0)&&(tc=0)&&(tr=0)&&(tc<8)) if((tr!=r) && (tc!=c)) attacks += (brd[tr][tc]=='Q'); } return(attacks); } int _tmain(int argc, _TCHAR* argv[]) { char *board[8]; int *attackers[8]; while(1) { for(int r=0;r<8;r++) // main search loop { board[r] = new(char[8]); for(int c=0;c<8;c++) board[r][c] = ' '; attackers[r] = new(int[8]); } for(int c =0;c<8;c++) { int r = rand()%8; board[r][c] = 'Q'; } int attempts = 0; while(attempts<10) { // number of attackers for(int r=0;r<8;r++) for(int c=0;c<8;c++) attackers[r][c] = pairs(board,r,c); // if the sum of the attackers at the queen positions = 0; done int attacks =0; for(int r=0;r<8;r++) for(int c=0;c<8;c++) attacks += (board[r][c]=='Q')?pairs(board,r,c):0; if (attacks == 0) { printf("\n FOUND ONE*********"); // Found a solution to the problem printf("\n Queens"); // prints out the board for(int r=0;r<8;r++) { printf("\n %d:",r); for(int c=0;c<8;c++) printf("%c",board[r][c]); } printf("\n"); break; } // find min int min = 8; int minr=0; int minc=0; for(int r=0;r<8;r++) for(int c=0;c<8;c++) if(attackers[r][c]<min) { min = attackers[r][c]; minr=r; minc=c; } // move the queen to that spot for(int r=0;r<8;r++) board[r][minc] = ' '; board[minr][minc] = 'Q'; // dump the board attempts++; } } return 0; }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)