漫水填充算法
给定一个矩阵;该矩阵表示一个屏幕。屏幕的每个元素 (i, j) 表示为像素,该像素的颜色以不同数字标记。在此算法中,当像素已经为上一次选择的颜色时,像素将填充为新颜色。如果上一个颜色不是上一个颜色,则不会填充该像素。填充像素后,它将检查其上方、下方、左侧和右侧的像素以执行相同的操作。
思路很简单,首先,我们检查选定的位置是否已用上一次的颜色着色,如果没有,算法将不工作。否则,它将使用新颜色填充该像素,并对它的四个相邻位置进行递归。
输入和输出
Input: The screen matrix: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 1 1 1 2 2 2 2 0 1 0 1 1 1 2 2 0 1 0 1 1 1 2 2 2 2 0 1 1 1 1 1 2 1 1 1 1 1 1 1 2 2 1 Output: Screen matrix after flood fill 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 1 1 1 3 3 3 3 0 1 0 1 1 1 3 3 0 1 0 1 1 1 3 3 3 3 0 1 1 1 1 1 3 1 1 1 1 1 1 1 3 3 1
算法
fillScreen(x, y, prevColor, newColor)
输入:开始的 (x,y) 坐标、上一次的颜色和新颜色。
输出 − 如果可能,将屏幕上的颜色从上一次更改为新的。
Begin if (x, y) not in the screen range, then return if color of (x, y) ≠ prevColor, then return screen[x, y] := newColor fillScreen(x+1, y, prevColor, newColor) fillScreen(x-1, y, prevColor, newColor) fillScreen(x, y+1, prevColor, newColor) fillScreen(x, y-1, prevColor, newColor) End
示例
#include<iostream> #define M 8 #define N 8 using namespace std; int screen[M][N] = { //the screen dimention and colors {1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 1}, {1, 2, 2, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 2, 2, 0}, {1, 1, 1, 1, 1, 2, 1, 1}, {1, 1, 1, 1, 1, 2, 2, 1} }; void fillScreen(int x, int y, int prevColor, int newColor) { //replace previous color of (x,y), with new color if (x < 0 || x >= M || y < 0 || y >= N) //when point exceeds the screen return; if (screen[x][y] != prevColor) //if the point(x,y) are not containing prevColor, do nothing return; screen[x][y] = newColor; //update the color fillScreen(x+1, y, prevColor, newColor); //for the right of (x,y) fillScreen(x-1, y, prevColor, newColor); //for the left of (x,y) fillScreen(x, y+1, prevColor, newColor); //for the top of (x,y) fillScreen(x, y-1, prevColor, newColor); //for the bottom of (x,y) } void floodFill(int x, int y, int newColor) { int prevColor = screen[x][y]; //take the color before replacing with new color fillScreen(x, y, prevColor, newColor); } int main() { int x = 4, y = 4, newColor = 3; cout << "Previous screen: "<< endl; for (int i=0; i<M; i++) { for (int j=0; j<N; j++) cout << screen[i][j] << " "; cout << endl; } cout << endl; floodFill(x, y, newColor); //start from (4, 4), with new color 3 cout << "Updated screen: "<< endl; for (int i=0; i<M; i++) { for (int j=0; j<N; j++) cout << screen[i][j] << " "; cout << endl; } }
输出
Previous screen 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 1 1 1 2 2 2 2 0 1 0 1 1 1 2 2 0 1 0 1 1 1 2 2 2 2 0 1 1 1 1 1 2 1 1 1 1 1 1 1 2 2 1 Updated screen: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 1 1 1 3 3 3 3 0 1 0 1 1 1 3 3 0 1 0 1 1 1 3 3 3 3 0 1 1 1 1 1 3 1 1 1 1 1 1 1 3 3 1
广告