Paint Fill - CtCI 8.10 (BFS)
by Hari Menon
JavaScript
'use strict';
var counter = 0,
color = {
Black: 0,
White: 1,
Red: 2,
Yellow: 3,
Green: 4
};
function paintFill(screen, row, column, newColor) {
if (screen[row][column] === newColor) return false;
return paintFillRecursive(screen, row, column, screen[row][column], newColor);
}
function paintFillRecursive(screen, r, c, oColor, nColor) {
var pointsToPaintQueue = [];
pointsToPaintQueue.push({
r: r,
c: c
});
var currentPoint = pointsToPaintQueue.shift();
while (currentPoint) {
console.log(++counter, 'Inside the loop', currentPoint.r, currentPoint.c);
if (!(currentPoint.r < 0 || currentPoint.r >= screen.length || currentPoint.c < 0 || currentPoint.c >= screen[0].length)) {
if (screen[currentPoint.r][currentPoint.c] === oColor) {
screen[currentPoint.r][currentPoint.c] = nColor;
pointsToPaintQueue.push({
r: currentPoint.r - 1,
c: currentPoint.c
}, {
r: currentPoint.r + 1,
c: currentPoint.c
}, {
r: currentPoint.r,
c: currentPoint.c - 1
}, {
r: currentPoint.r,
c: currentPoint.c + 1
});
}
}
currentPoint = pointsToPaintQueue.shift();
}
return true;
}
var screen = [
[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, 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, 1, 1, 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, 1, 1, 1, 1, 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, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...