Counting equal numbers that appear directly next to each other

4 visualizzazioni (ultimi 30 giorni)
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 30x30) 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.
  1 Commento
Kirby Fears
Kirby Fears il 11 Dic 2015
Try making a function that performs the first step (given a matrix with 1's, 0's, and a single 2 not on the boundary) and returns the matrix with 3's added where possible.
Then try adding recursion inside of your function (at the end).

Accedi per commentare.

Risposta accettata

Kirby Fears
Kirby Fears il 11 Dic 2015
.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
  1 Commento
Menno Martens
Menno Martens il 11 Dic 2015
I eventually did it like this and also worked really well for me, thank you for the inspiration though
function maze_escape = maze(y,x,m)
if m(x,y) == 1
warning('knight not placed on an open spot')
else
m(x,y) = 2;
[r c] = find(m==2);
steps = 2;
while 1
[r c] = find(m==(steps));
rc = [r c];
if any(r == length(m)) || any(c == length(m)) || any(r == 1) || any(c == 1)
break
end
for i = 1:length(rc(:,1))
idx = rc(i,1);
idy = rc(i,2);
if m(idx+1,idy) == 0
m(idx+1,idy) = steps+1;
end
if m(idx-1,idy) == 0
m(idx-1,idy) = steps+1;
end
if m(idx,idy+1) == 0
m(idx,idy+1) = steps+1;
end
if m(idx,idy-1) == 0
m(idx,idy-1) = steps+1;
end
end
steps = steps + 1;
end
if ismember(steps,m(length(m),:)) || ismember(steps,m(:,length(m))) || ismember(steps,m(1,:)) || ismember(steps,m(:,1))
steps = steps-2
m
else
steps = 0
m
end
end

Accedi per commentare.

Più risposte (1)

Image Analyst
Image Analyst il 12 Dic 2015

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by