Function representing a forest fire after one time step
Here is an example. First we need some data:
n = 5;
mat = RandomChoice[{0, 1, 2}, {n, n}];
Then we need a function that shifts a list to the left or right, filling the empty place with zeros. It is nearly the same functionality as RotateRight/Left, but we do not want it to be circular. Therefore we set the elements that are circulated to zero.
shiftr[m_] := Prepend[Rest[RotateRight[m]], 0 m[[1]]]
shiftl[m_] := Append[Most[RotateLeft[m]], 0 m[[1]]]
We define now a step: With the help of shiftr/l
we shift the current matrix left/right/up/down and take the maximum at every position, that gives a matrix mat1
with 2 at all the shifted positions of 2's. Finally we imprint this shifted 2's onto the the matrix mat
:
step[mat_] := (mat1 =
MapThread[
Max, {shiftr[mat], shiftl[mat], shiftr /@ mat, shiftl /@ mat},
2]; MapThread[If[#2 == 2, 2, #1] &, {mat, mat1}, 2]);
Now we apply this to our data:
mat // MatrixForm
(mat = step[mat]) // MatrixForm
(mat = step[mat]) // MatrixForm
ClearAll[vNNeighbors, nextStep]
vNNeighbors[dim_] := AdjacencyList[NearestNeighborGraph @ Tuples @ Range @ dim, #]&
nextStep = MapAt[Min[2, 2 #] &, #, vNNeighbors[Dimensions @ #][Position[#, 2]]] &;
Example :
SeedRandom[1]
mat = RandomChoice[{0, 1, 2}, {10, 10}];
Row[MapThread[Labeled[#, #2, Top] &,
{MatrixForm /@ {mat /. 2 -> Highlighted[2],
nextStep[mat] /. 2 -> Highlighted[2, Background -> RGBColor[1, 0, 1]]},
{Style["mat" , 16], Style["nextStep[mat]", 16]}}], Spacer[10]]
Use nextStep
with NestList
to simulate spreading of 2
s in the initial matrix mat
:
SeedRandom[1]
mat = RandomChoice[{49, 50, 1} -> {0, 1, 2}, {40, 40}];
timesteps = 60;
frames = MatrixPlot[# /. {0 -> White, 1 -> Green, 2 -> Red}, Mesh -> All,
ImageSize -> 400] & /@ NestList[nextStep, mat, timesteps];
ListAnimate[frames]