[CareerCup] 9.7 Paint Fill 填充

Grandyang發表於2015-09-23

 

9.7 Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color.

 

這道題是一道填充問題,有點類似於Flash中的油桶工具,就是給指定的位置填充顏色,如果要填充的顏色和原來的顏色相同,則不發生變換,如果不同的話,則把相連線的區域都填充為新的顏色。那麼我們使用遞迴來做,首先判斷要填充的顏色和該位置上原有的顏色是否相同,如果不同的話就開始填充,如果周圍顏色和起始位置顏色相同也填充,參見程式碼如下:

 

enum Color { Black, White, Red, Yellow, Green };

class Solution {
public:
    bool paintFill(vector<vector<Color> > &screen, int x, int y, Color newColor) {
        if (screen[x][y] == newColor) return false;
        return paintFill(screen, x, y, screen[x][y], newColor);
    }
    bool paintFill(vector<vector<Color> > &screen, int x, int y, Color oldColor, Color newColor) {
        if (x < 0 || x >= screen.size() || y < 0 || y >= screen[0].size()) return false;
        if (screen[x][y] == oldColor) {
            screen[x][y] = newColor;
            paintFill(screen, x - 1, y, oldColor, newColor);
            paintFill(screen, x + 1, y, oldColor, newColor);
            paintFill(screen, x, y - 1, oldColor, newColor);
            paintFill(screen, x, y + 1, oldColor, newColor);
        }    
        return true;
    }
};

 

相關文章