Code covered by the BSD License

# Max Path for grayscale 2D image

by

### ja (view profile)

max path using dynamic programming

mxpth(II)
```function IJ = mxpth(II)
%returns a linearly indexed max path of a 2D image
%for min path simply set II = -II;
[m n] = size(II);
IK = II-min(II(:));
IJ = zeros(n,1);
for i=1:n-1
v1 =[IK(2:m,i)' 0];
v2 = IK(:,i)';
v3 = [0 IK(1:m-1,i)'];

%if weights are desired, put them here
k = max([v1;v2;v3])';
IK(:,i+1) = IK(:,i+1)+k;
end
IK(1:10,:) = 0;
IK(m-10:m,:) = 0;
v1 = find(IK == max(IK(:)));
IJ(n) = v1(numel(v1));
for i=1:n-1
k = IJ(n-i+1)-m;
if k == 1
if IK(k+1) > IK(k)
IJ(n-i) = k+1;
else
IJ(n-i) = k;
end
else
if k == m
if IK(k-1) > IK(k)
IJ(n-i) = k-1;
else
IJ(n-i) = k;
end
else
if IK(k+1) > IK(k) && IK(k+1) > IK(k-1)
IJ(n-i) = k+1;
else
if IK(k-1) > IK(k) && IK(k-1)>IK(k+1)
IJ(n-i) = k-1;
else
IJ(n-i) = k;
end
end
end
end
end

%if you do not want linear indexing, comment out the below
% IJ(:,2) = mod(IJ(:,1),m);
% IJ(IJ==0) = m;
% IJ(:,1) = IJ(:,1) - IJ(:,2);
% IJ(:,1) = IJ(:,1)*(1/m)+1;

end```