Professional Documents
Culture Documents
8 Queen
8 Queen
8 Queen
This problem is to place 8 queens on the chess board so that they do not attack each other hori zontally, vertically or diagonally. It turns out that there are 12 essentially d istinct solutions to this problem. Suppose we have an array t[8] which keeps track of which column is occupied in w hich row of the chess board. That is, if t[0]==5, then it means that the queen h as been placed in the fifth column of the first row. We need to couple the backt racking algorithm with a procedure that checks whether the tuple is completable or not, i.e. to check that the next placed queen 'i' is not menaced by any of th e already placed 'j' (j < i): Two queens are in the same column if t[i]=t[j] Two queens are in the same major diagonal if (t[i]-t[j])=(i-j) two queens are in the same minor diagonal if (t[j]-t[i])=(i-j)
Here is some working C code to solve this problem using backtracking #include static int t[10]={-1}; void queens(int i); int empty(int i); void print_solution(); int main() { queens(1); print_solution(); return(0); } void queens(int i) { for(t[i]=1;t[i]<=8;t[i]++) { if(empty(i)) { if(i==8) { print_solution(); /* If this exit is commented, it will show ALL possible combinations */ exit(0); } else { // Recurse! queens(i+1); } }// if }// for }
[1] // This means the first square of the first row. [5] // This means the fifth square of the second row. [8] .. [6] .. [3] .. [7] .. [2] .. [4] // This means the fourth square of the last row. by Vijay Agrawal at 3:24 PM