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

Learn moreOpportunities for recent engineering grads.

Apply TodayWrite 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.)

76 correct solutions
110 incorrect solutions

Last solution submitted on Oct 11, 2014

2 players like this problem

1 player likes this solution

1 Comment

Andrew Newell
on 25 Apr 2014

The beauty of this solution is that you can use it for any other side board (e.g., isEightQueensSolution([1 0; 0 1]) ).

5 Comments

Show
2 older comments

Steve Eddins
on 11 Feb 2012

Doesn't this kind of trick get boring after a while?

@bmtran
on 11 Feb 2012

actually, this is the first time i've used it without essentially copying Alfonso's code, so it's still new and fresh for me =P

Benjamin Kraus
on 12 Feb 2012

Can someone explain to me how this function works (even if it is a trick)? I'm trying to parse through the code, but how it works isn't clear to me.

@bmtran
on 12 Feb 2012

the sparse function places the values (third input) into the row and column specified, 1st and second inputs respectively. if there are any overlapping coordinates then it sums them, so I created a matrix that, when fed into sparse, would sum the rows, sum the columns, and sum the diagonals in each direction. Then I Cody-fied it (teehee) by changing these indices into a string of characters, which Cody sizes as small, and subtracting a base character from it. does that make sense now?

@bmtran
on 12 Feb 2012

it might make more sense to look at one of my other solutions that uses the str2num function instead of the letter thing...

2 Comments