MATLAB Write a function called queen_check that takes an 8-by-8 logical array ca
ID: 3769056 • Letter: M
Question
MATLAB
Write a function called queen_check that takes an 8-by-8 logical array called board as input. The variable board represents a chessboard where a true element means that there is a queen at the given position (unlike in chess, there can be up to 64 queens!), and false means that there is no piece at the given position. The function returns true if no two queens threaten each other and false otherwise. One queen threatens the other if they are on the same row, on the same column, or on the same diagonal.
Explanation / Answer
function [newboard] = place(board, nqueens)
arrsize=size(board);
nrows=arrsize(1);
ncols=arrsize(2);
newboard=false;
if (nqueens==0) newboard=board;
else
for i=1:nrows
for j=1:ncols
if (testsafe(board, i, j))
temp=board;
temp(i,j)=1;
temp=place(temp,nqueens-1);
if (size(temp)==arrsize)
newboard=temp;
return;
end
end
end
end
end
end
function [safe] = testsafe(board, row, col)
safe=true;
if sum(board(row,:)) > 0
safe=false;
elseif sum(board(:,col))> 0
safe= false;
elseif sum(diag(board,col-row))>0
safe= false;
else
rotated=rot90(board);
newcol=row;
newrow=(8-col)+1;
if sum(diag(rotated,newcol-newrow))>0
safe= false;
end
end
return;
end
function void = printb(barr, nqueens)
bsize=size(barr);
cols=bsize(2);
rows=bsize(1);
hitsx=[];
hitsy=[];
missx=[];
missy=[];
for i= 1:rows
for j=1:cols
if barr(i,j)
hitsy(end+1)=rows-i;
hitsx(end+1)=j;
else
missy(end+1)=rows-i;
missx(end+1)=j;
end
end
end
bx=[-1, cols+1];
by=[-1, rows+1];
plot(hitsx,hitsy,'r*',missx,missy,'bo',bx,by,'.');
tstr=['Plot of ' num2str(nqueens) ' queens placed on ' num2str(rows) ' by ' num2str(cols) ' chessboard'];
title(tstr);
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.