1. Description of the problem
The eight Queens question was introduced in 1850 by the famous mathematician Gauss in 19th century. The problem is: put 8 queens on the 8*8 board so that they cannot attack each other, that is, any two queens cannot be in the consent line, the same column, or the agreed slash.
2.matlab Code
function Placequeen (row,stack,n)% backtracking Place Queen if Row>n Printqueen (n,stack);% print checkerboard else for col=1:n Stack ( Row) =col; If row==1| | Conflict (row,col,n,stack)% detect conflict Placequeen (row+1,stack,n); End Stack (row) =0; EndEnd% Sub function: Detect conflict function result=conflict (row,col,n,stack)% detect conflict result=1;for i=1:row-1 if stack (i) ~=0 if (( Stack (i) ==col) | | (ABS (Row-i) ==abs (Col-stack (i))) % conflict: In the same line, Slash on result=0; break; End if result==0 break ; End endend%: Print checkerboard information function printqueen (n,stack) global solutionnum;% define global variables to accumulate the number of methods solutionnum=solutionnum+1 ; Disp ([' num2str ', ' solutionnum ', ' method: ') ' for i=1:n for j=1:n if J==stack (i) fprintf (' 1 ') else fprintf (' 0 ') end End fprintf (' \ n ') end
placequeen.m
Clear ALLCLC Global solutionnum;solutionnum=0;% number of record methods n=8;% Queens number%matrix=zeros (N);% Store Queens location information stack=[0 0 0 0 0 0 0 0]; Placequeen (1,stack,n)% call placement method
queen.m
Eight Queens Problem-backtracking method (MATLAB)