JSFiddle - React, Tailwind, and code Playground
by kpulkit29
JavaScript
let input = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
function colorArr(input, x, y, color) {
let originalColor = input[x][y];
let dirs = [
[-1, 0],
[1, 0],
[0, 1],
[0, -1]
];
function createGraph(p1, p2) {
for (let dir of dirs) {
let [x, y] = dir;
let newX = p1+x;
let newY = p2+y;
if(newX<0 || newX>=input.length || newY<0 || newY>=input[0].length || input[newX][newY] === color) {
continue;
} else if(input[newX][newY] != originalColor) {
continue;
} else {
//mp[[p1,p2]].push([newX, newY]);
input[newX][newY] = color;
createGraph(newX, newY);
}
}
}
input[x][y] = color;
createGraph(x, y);
console.log(input);
}
colorArr(input, 5,5, 2);