Comments on: The Eight Queens Problem https://blogs.mathworks.com/steve/2017/04/20/the-eight-queens-problem/?s_tid=feedtopost Retired from MathWorks in 2024 after 30 years of service. Can now be found at MATLAB Central, https://hornjourney.com, and https://matrixvalues.com. MathWorks career included image processing, toolbox development, MATLAB development and design, development team management, MATLAB design standards, Steve on Image Processing blog (https://blogs.mathworks.com/steve). Co-author of Digital Image Processing Using MATLAB (https://www.imageprocessingplace.com/DIPUM-3E/dipum3e_main_page.htm). French horn enthusiast, member of Concord Orchestra and Melrose Symphony, member of the board of Cormont Music and the Kendall Betts Horn Camp. Fri, 01 Nov 2019 21:08:44 +0000 hourly 1 https://wordpress.org/?v=6.2.2 By: michael https://blogs.mathworks.com/steve/2017/04/20/the-eight-queens-problem/#comment-28854 Fri, 04 Aug 2017 11:47:51 +0000 https://blogs.mathworks.com/steve/?p=2558#comment-28854 sorry guys i forget the other diagonal
function [board,succeeded] = placeQueens(board,col)

N = size(board,1);
if col > N
% There are no columns left. All the queens
% have been placed. Return with success.
succeeded = true;
return
end

safe = false(1,N);
for row = 1:N
safe(row) = isSafe(board,row,col);
end

if ~any(safe)
% There are no safe squares on this column.
% Return with failure.
succeeded = false;
return
end

for row = 1:N
if safe(row)
board(row,col) = 1;
[board,succeeded] = placeQueens(board,col+1);
if succeeded
return
else
% Backtrack. Undo the placement of the queen
% on this column and keep looking.
board(row,col) = 0;
end
end
end

% If we get here, we have checked every row on this column
% without succeeding. Return with failure.
succeeded = false;
end

function [ safe] = isSafe(board,row,col)
safe =true;
% row
if(sum(board(row,:)>0))
safe = false;
return ;
end

if(sum(board(:,col)>0))
safe = false;
return ;
end

% ncol=floor(size(board,2)/2)+1;
dcol = col-row;

if(sum(diag(board,dcol)>0))
safe = false;
return ;
end

NewcolN=size(board,2)-col+1;
dcol = NewcolN-row;

if(sum(diag(fliplr(board),dcol)>0))
safe = false;
return ;
end

end

====
also nice way to viiew the solution
figure;imshow((board),’InitialMagnification’,’fit’)

]]>
By: michael https://blogs.mathworks.com/steve/2017/04/20/the-eight-queens-problem/#comment-28853 Fri, 04 Aug 2017 11:27:09 +0000 https://blogs.mathworks.com/steve/?p=2558#comment-28853 the function is safe has tricky part of checking the diagonal , so i added my solution
function [ safe] = isSafe(board,row,col)
safe =true;
% row
if(sum(board(row,:)>0))
safe = false;
return ;
end

if(sum(board(:,col)>0))
safe = false;
return ;
end

% ncol=floor(size(board,2)/2)+1;
dcol = col-row;

if(sum(diag(board,dcol)>0))
safe = false;
return ;
end

end

]]>