-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbucket-fill-tool-recursion.js
48 lines (37 loc) · 1.36 KB
/
bucket-fill-tool-recursion.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var field = [
[ 'O', 'X', 'X', 'X', 'X' ],
[ 'X', 'O', 'O', 'O', 'X' ],
[ 'X', 'O', '#', 'O', 'X' ],
[ 'X', '*', '*', '*', 'X' ],
[ 'X', 'X', 'O', 'X', 'X' ],
[ 'X', 'X', 'X', '#', '#' ],
[ 'X', 'O', 'X', 'X', 'X' ]
];
function fill(field, x, y, color, replaceColor, setted) {
setted = setted || [];
if (setted.indexOf(x + ', ' + y) !== -1) return;
if (x < 0 || x > (field[0].length - 1) ||
y < 0 || y > (field.length - 1)) return;
replaceColor = replaceColor || field[y][x];
if (field[y][x] != replaceColor && field[y][x] != color) return;
field[y][x] = color;
setted.push(x + ', ' + y);
fill(field, x - 1, y - 1, color, replaceColor, setted);
fill(field, x - 1, y, color, replaceColor, setted);
fill(field, x - 1, y + 1, color, replaceColor, setted);
fill(field, x, y - 1, color, replaceColor, setted);
fill(field, x, y + 1, color, replaceColor, setted);
fill(field, x + 1, y - 1, color, replaceColor, setted);
fill(field, x + 1, y, color, replaceColor, setted);
fill(field, x + 1, y + 1, color, replaceColor, setted);
}
// fill(field, 0, 0, '*');
// console.log(field);
//
// [ [ '*', 'X', 'X', 'X', 'X' ],
// [ 'X', '*', '*', '*', 'X' ],
// [ 'X', '*', '#', '*', 'X' ],
// [ 'X', '*', '*', '*', 'X' ],
// [ 'X', 'X', '*', 'X', 'X' ],
// [ 'X', '*', 'X', '#', '#' ],
// [ 'X', '*', 'X', 'X', 'X' ] ]