Paint Fill - CtCI 8.10 (DFS)
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) {
// console.log(++counter, 'Inside paintFillRecursive');
if (r < 0 || r >= screen.length || c < 0 || c >= screen[0].length) {
return false;
}
if (screen[r][c] === oColor) {
screen[r][c] = nColor;
paintFillRecursive(screen, r - 1, c, oColor, nColor); // up
paintFillRecursive(screen, r + 1, c, oColor, nColor); // down
paintFillRecursive(screen, r, c - 1, oColor, nColor); // left
paintFillRecursive(screen, r, c + 1, oColor, nColor); // right
}
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, 1, 1, 1, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 1, 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]
];
console.log(screen.map(function (r) {
return r.join('');
}).join('\n'));
paintFill(screen, 4, 12, color.Green);
console.log(screen.map(function (r) {
return r.join('');
}).join('\n'));
paintFill(screen, 0, 12,...