Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
By R. Kishore Kumar
1 2 3 . . . .
1 .
1 . . 2 3 .
1 2 . 4
8-Queen problem
Chessboards squares being numbered as the indices of two dimensional array a[1:n][1:n]. We can observe that every element on the same diagonal that runs from upper left to lower right has the same row-column value.
Solution of 8-Queen
1 2 3 4 5 6 3 4 5 1 2
(8,5,4,3,2) = 1649
(8,5,3,1,2,1) = 769
6
7 8 (8,6,4,2,1,1,1) = 1401 (8,6,4,3,2) = 1977 (8,5,3,2,2,1,1,1) = 2329
Bool Place(int k, int i) //Returns true if a queen can be placed in kth row //and ith column. Otherwise it returns false. x[] //is a global array whose first (k-1) values have //been set. Abs(r) returns the absolute value of r { for(int j=1; j<k; j++) if((x[j]==i)//Two in the same column || (abs(x[j]-i)==abs(j-k))) //or in the same diagonal return(false); return(true); }
void NQueens(int k,int n) //Using backtracking,this procedure prints all //possible placements of n queens on an nxn //chessboard so that they are nonattacking { for(int i=1;i<n;i++) { if(Place(k,i)) { x[k]=i; if(k==n) { for(int j=1;j<=n;j++) cout<<x[j]<<' ': cout<<endl; } else NQueens(k+1,n); } } }
Algorithm explanation
For an 8*8 chessboard there are (648) possible ways to place 8 pieces. Placement of each queen on the chessboard was chosen randomly. With each choice we keep track of number of columns a queen could legitimately be placed on.
)]
THANK YOU!!!