好干涸,奔男人和猫# pets - 心有所宠
g*j
1 楼
Implement the “paint fill” function that one might see on many image
editing programs. That is, given a screen (represented by a 2-dimensional
array of Colors), a point, and a new color, fill in the surrounding area
until you hit a border of that color.
我看到最近版上不好题目提到了 150上提到的答案如下,我有几个疑问
1 什么叫“until you hit a border of that color”
2 为什么只考虑四个点?不是8个点?8个点有重复的吧?
3 递归的时候这四个点的顺序不一样,会有问题么?
We can implement this algorithm recursively:
1 enum Color {
2 Black, White, Red, Yellow, Green
3 }
4 boolean PaintFill(Color[][] screen, int x, int y, Color ocolor,
5 Color ncolor) {
6 if (x < 0 || x >= screen[0].length ||
7 y < 0 || y >= screen.length) {
8 return false;
9 }
10 if (screen[y][x] == ocolor) {
11 screen[y][x] = ncolor;
12 PaintFill(screen, x - 1, y, ocolor, ncolor); // left
13 PaintFill(screen, x + 1, y, ocolor, ncolor); // right
14 PaintFill(screen, x, y - 1, ocolor, ncolor); // top
15 PaintFill(screen, x, y + 1, ocolor, ncolor); // bottom
16 }
17 return true;
18 }
19
20 boolean PaintFill(Color[][] screen, int x, int y, Color ncolor) {
21 return PaintFill(screen, x, y, screen[y][x], ncolor);
22 }
editing programs. That is, given a screen (represented by a 2-dimensional
array of Colors), a point, and a new color, fill in the surrounding area
until you hit a border of that color.
我看到最近版上不好题目提到了 150上提到的答案如下,我有几个疑问
1 什么叫“until you hit a border of that color”
2 为什么只考虑四个点?不是8个点?8个点有重复的吧?
3 递归的时候这四个点的顺序不一样,会有问题么?
We can implement this algorithm recursively:
1 enum Color {
2 Black, White, Red, Yellow, Green
3 }
4 boolean PaintFill(Color[][] screen, int x, int y, Color ocolor,
5 Color ncolor) {
6 if (x < 0 || x >= screen[0].length ||
7 y < 0 || y >= screen.length) {
8 return false;
9 }
10 if (screen[y][x] == ocolor) {
11 screen[y][x] = ncolor;
12 PaintFill(screen, x - 1, y, ocolor, ncolor); // left
13 PaintFill(screen, x + 1, y, ocolor, ncolor); // right
14 PaintFill(screen, x, y - 1, ocolor, ncolor); // top
15 PaintFill(screen, x, y + 1, ocolor, ncolor); // bottom
16 }
17 return true;
18 }
19
20 boolean PaintFill(Color[][] screen, int x, int y, Color ncolor) {
21 return PaintFill(screen, x, y, screen[y][x], ncolor);
22 }