% queen attacks test % This program finds the number of attacks between the queens % on the board. Queens are represented by 1s, empty places are represented by 0s. % The board size is N. clear clc N=5; % A = ones(N); A=rand(N)>0.5; % A = [1 1 0 1 1; 0 1 0 1 0; 1 1 0 0 1; 0 1 1 1 0; 0 0 1 1 1]; num_attacks = 0; % count horizontal attacks for i = 1 : N temp = sum(A(i, :)); if (temp < 2) temp2 = 0; else temp2 = cumsum(1 : temp - 1); temp2 = temp2(end); end num_attacks = num_attacks + temp2; end % count vertical attacks for i = 1 : N temp = sum(A(:, i)); if (temp < 2) temp2 = 0; else temp2 = cumsum(1 : temp - 1); temp2 = temp2(end); end num_attacks = num_attacks + temp2; end % count diagonal attacks for i = -(N-2) : (N-2) temp = sum(diag(A, i)); if (temp < 2) temp2 = 0; else temp2 = cumsum(1 : temp - 1); temp2 = temp2(end); end num_attacks = num_attacks + temp2; end % count antidiagonal attacks A = fliplr(A); for i = -(N-2) : N-2 temp = sum(diag(A, i)); if (temp < 2) temp2 = 0; else temp2 = cumsum(1 : temp - 1); temp2 = temp2(end); end num_attacks = num_attacks + temp2; end