I want to know how to change this algorithm to return new array of updated things instead of changing it in global map array. It's using JS implementation of Flood Fill algorithm.
This is the array I have:
var map = [
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 1]
];
And this is the result I want to get out of calling my floodFill function:
result = [
[0, 2, 2],
[0, 2, 0],
[2, 2, 0],
[0, 2, 0]
];
Here is the whole source(that's just changing connected ones in original array to twos):
var map = [
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 1]
];
function floodFill(data, x, y, newValue) {
// get target value
var target = data[x][y];
function flow(x,y) {
// bounds check what we were passed
if (x >= 0 && x < data.length && y >= 0 && y < data[x].length) {
if (data[x][y] === target) {
data[x][y] = newValue;
flow(x-1, y);
flow(x+1, y);
flow(x, y-1);
flow(x, y+1);
}
}
}
flow(x,y);
}
var result = floodFill(map, 1, 3, 2);
/*
result = [
[0, 2, 2],
[0, 2, 0],
[2, 2, 0],
[0, 2, 0]
]
*/