MATLAB: Counting equal numbers that appear directly next to each other

Image Processing Toolboxmatrixpathshortest path algorithm

I'm trying to achieve this for a while now but I can't figure out to do this in an easy and understandable way.. Imagine a 2D-matrix(e.g 30×30) containg ones and zeros. there is an inital position on one of the zeros in the matrix, this zero then becomes a 2. Now, if the 2 has any 0 above/below or left/right, make these zeros 3. then do the same for 3 and so on untill it reaches the boundary of the matrix(In this case the ouput is the smallest value it reaches the boundary with) or it cannot reach the boundary of the matrix(In that case the output =0)
This is essentially a shortest path finder for a labyrinth in a matrix of zeros and ones. where zeros represent an open path and ones the walls.

Best Answer

.m:
function [maxVal,nSteps,m] = escapeMaze(m,wallVal)
mStartVal = max(m(:));
[m,status] = stepMaze(m,wallVal);
maxVal = max(m(:));
nSteps = maxVal - mStartVal;
if ~status,
maxVal = 0;
end
end
function [m,status] = stepMaze(m,wallVal)
status = true;
n = size(m,1);
mMax = max(m(:));
idx = find(m==mMax);
idxStep = idx + [-1,1,-n,n]';
idxStep = idxStep(m(idxStep)~=wallVal);
if isempty(idxStep),
warning('Maze cannot be escaped.');
status = false;
return;
end
m(idxStep) = mMax+1;
modVals = mod(idxStep,n);
if ~any(idxStep>(numel(m)-n) | idxStep<=n ...
| modVals==1 | modVals==0),
m = stepMaze(m);
end
end