MATLAB: Puzzler: Quickly tell if two absolute indices (a,b) are four connected for n x m matrix.

puzzler

function flag = isFourConnected(a,b,n,m)
%


% a,b: indices of interest a ~= b
% n,m: size of matrix of interest
%
% flag: True if indices a and b are four connected
% in a matrix of size n x m
%
%
% Your code here
Note, this code should use no toolboxes, and should be reasonably quick as this function will be called many times. Reasonably quick is up to debate as the rest of the code forms.

Best Answer

function flag = isFourConnected(a,b,n,m)
%

% a,b: indices of interest a ~= b
% n,m: size of matrix of interest
%
% flag: True if indices a and b are four connected
% in a matrix of size n x m
%
d = abs(a-b);
flag = d == n || (d == 1 && mod(min(a,b), n));
end
Related Question