Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!

Problem 306. Eight Queens Solution Checker

Created by Steve Eddins

Write a function to verify whether an arrangement of queens on a chessboard is a valid solution to the classic eight queens problem.

In the eight queens problem, eight queens must be placed on a chessboard such that no two queens attack each other. That is, no two queens can share the same row, column, or diagonal. The diagram below is one possible solution:

Your function should take an 8-by-8 matrix of 0s and 1s, where the 1s represent the position of the queens, and return a logical 1 if the solution is valid or a logical 0 otherwise.

EXAMPLE 1

   in1 = [ ...
       0 0 0 1 0 0 0 0
       0 0 0 0 0 0 1 0
       0 0 1 0 0 0 0 0
       0 0 0 0 0 0 0 1
       0 1 0 0 0 0 0 0
       0 0 0 0 1 0 0 0
       1 0 0 0 0 0 0 0
       0 0 0 0 0 1 0 0 ];
   isEightQueensSolution(in1)

returns 1.

EXAMPLE 2

   in2 = [ ...
       0 0 0 1 0 0 0 0
       0 0 0 0 0 0 1 0
       0 0 1 0 0 0 0 0
       0 0 0 0 0 0 0 1
       0 1 0 0 0 0 0 0
       1 0 0 0 0 0 0 0
       0 0 0 0 1 0 0 0
       0 0 0 0 0 1 0 0 ];
   isEightQueensSolution(in2)

returns 0. (Notice that the queens on the bottom two rows share a diagonal.)

Tags

Problem Group

Solution Statistics

102 correct solutions 176 incorrect solutions
Last solution submitted on Jul 22, 2016

Problem Comments

Solution Comments