Python example sharing --- logic reasoning programming solution to eight queens

Source: Internet
Author: User
The eight queens issue is an ancient and famous issue and is a typical case of backtracking algorithms. This problem was raised by Max & #183, an international chess player, who proposed in 1848 that eight queens should be placed on 8x8 chess so that they could not attack each other, that is to say, neither of the two queens can be in the same row, column, or diagonal line. It can match the pattern like Haskell and Prolog,

Create logic to push to rules, describe the question, and get the answer.

from pyDatalog import pyDatalogpyDatalog.create_atoms( 'N, N1, X, Y, X0, X1, X2, X3, X4, X5, X6, X7' )pyDatalog.create_atoms( 'ok, queens, next_queen, pred, pred2' )size = 8ok( X1, N, X2 ) <= ( X1 != X2 ) & ( X1 != X2 + N ) & ( X1 != X2 - N )pred( N, N1 )  <= ( N > 1 ) & ( N1 == N - 1 )queens( 1, X ) <= ( X1._in( range( size ) ) ) & ( X1 == X[0] )queens( N, X ) <= pred( N, N1 ) & queens( N1, X[:-1] ) & next_queen( N, X )pred2( N, N1 )   <= ( N > 2 ) & ( N1 == N - 1 )next_queen( 2, X ) <= ( X1._in( range( 8 ) ) ) & ok( X[0], 1, X1 ) & ( X1 == X[1] )next_queen( N, X ) <= pred2( N, N1 ) & next_queen( N1, X[1:] ) & ok( X[0], N1, X[-1] ) print( queens( size, ( X0, X1, X2, X3, X4, X5, X6, X7 ) ) )

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.