📜  使用C图形的洪水填充算法

📅  最后修改于: 2021-05-28 03:21:12             🧑  作者: Mango

给定一个矩形,您需要使用洪水填充算法填充该矩形的任务。
例子:

输入:矩形(左= 50,上= 50,右= 100,底= 100)Flood(x = 55,y = 55,new_color = 12,old_color = 0)输出: 输入:矩形(左= 50,上= 50,右= 200,底= 400)Flood(x = 51,y = 51,new_color = 6,old_color = 0)输出:

填充算法会填充新颜色,直到
旧的颜色匹配。

洪水填充算法:-

// A recursive function to replace previous
// color 'oldcolor' at  '(x, y)' and all 
// surrounding pixels of (x, y) with new 
// color 'newcolor' and
floodfill(x, y, newcolor, oldcolor)
1) If x or y is outside the screen, then
   return.
2) If color of getpixel(x, y) is same as
   oldcolor, then 
3) Recur for top, bottom, right and left.
    floodFill(x+1, y, newcolor, oldcolor);
    floodFill(x-1, y, newcolor, oldcolor);
    floodFill(x, y+1, newcolor, oldcolor);
    floodFill(x, y-1, newcolor, oldcolor); 
// program to fill polygon using floodfill
// algorithm
#include 
#include 
  
// flood fill algorithm
void flood(int x, int y, int new_col, int old_col)
{
    // check current pixel is old_color or not
    if (getpixel(x, y) == old_col) {
  
        // put new pixel with new color
        putpixel(x, y, new_col);
  
        // recursive call for bottom pixel fill
        flood(x + 1, y, new_col, old_col);
  
        // recursive call for top pixel fill
        flood(x - 1, y, new_col, old_col);
  
        // recursive call for right pixel fill
        flood(x, y + 1, new_col, old_col);
  
        // recursive call for left pixel fill
        flood(x, y - 1, new_col, old_col);
    }
}
  
int main()
{
    int gd, gm = DETECT;
  
    // initialize graph
    initgraph(&gd, &gm, "");
  
    // rectangle coordinate
    int top, left, bottom, right;
  
    top = left = 50;
    bottom = right = 300;
  
    // rectangle for print rectangle
    rectangle(left, top, right, bottom);
  
    // filling start cordinate
    int x = 51;
    int y = 51;
  
    // new color to fill
    int newcolor = 12;
  
    // new color which you want to fill
    int oldcolor = 0;
  
    // call for fill rectangle
    flood(x, y, newcolor, oldcolor);
    getch();
  
    return 0;
}

输出:-

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。