Home > other >  On matlab n queen problem
On matlab n queen problem

Time:09-16

Today in an attempt to use matlab to solve the n queens problem, but the output of the board the result is always wrong, looked at half a day also don't see what's the problem, help you a great god help solve, thank you!
The code below
The input for the queen (zeros (m), m, 1)
M is the board size, the layer is to control the number of rows
 function queen (map, m, layer) 

If the sum (the sum (map))==m % recursion end condition
Disp (map);
% count also can't write
Return
End

For I=1: m % in each row of each position to try to put queen
If layer==1% the first line does not need to determine whether can put
The map (layer, I)=1;
Queen (map, m, layer + 1);
Elseif layer> 1

% to determine if I can put a

% to judge whether the column has been queen
Temp1=0;
For row=1: I
If the map (the row, I)==1
Temp1=temp1 + 1;
End
End

% judgment have upper left diagonally queen
Temp2=0;
K1=layer - 1;
If I & gt; 1
For left=I - 1
If k1 & gt;=1 & amp; & The map (k1, left)==1
Temp2=temp2 + 1;
Elseif k1 & lt; 1
Break
End
K1=k1-1;
End
End

% judgment right diagonally
Temp3=0;
K2=layer - 1;
If iFor the right=I + 1: m
If k2 & lt; 1
Break
Elseif k2 & gt;=1 & amp; & The map (k2, right)==1
Temp3=temp3 + 1;
End
K2=k2-1;
End
End

% if can put, iterative
If temp1==0 & amp; & Temp2==0 & amp; & Temp3==0
The map (layer, I)=1;
Queen (map, m, layer + 1); % to the next line began to put queen
The map (layer, I)=0;
End
End
End


End
  • Related