Eight Queens Problem-backtracking method (MATLAB)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.