I am seeking guidance on modifying this algorithm to generate a new array of updated elements instead of altering the global map array. This is the JavaScript implementation of the Flood Fill algorithm.
Starting Array:
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]
];
Desired Result after calling floodFill function:
result = [
[0, 2, 2],
[0, 2, 0],
[2, 2, 0],
[0, 2, 0]
];
Below is the code snippet (which changes connected ones in the 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]
]
*/