使用 C 圖形填充演算法


概念

對於給定的矩形,我們的任務是應用填充演算法來填充該矩形。

輸入 

rectangle(left = 50, top = 50, right= 100, bottom = 100)
floodFill( a = 55, b = 55, NewColor = 12, OldColor = 0)

輸出 

方式

// 一個遞迴函式,在 (a, b) 處將之前的顏色“OldColor”替換為新顏色“NewColor”,並將 (a, b) 的所有相鄰畫素也用新顏色填充,即 floodFill(a, b, NewColor, OldColor)

  • 如果 a 或 b 在螢幕外,則返回。

  • 如果 getpixel(a, b) 的顏色與 OldColor 相同,則

  • 遞迴遍歷上方、下方、右側和左側。

    floodFill(a+1, b, NewColor, OldColor);

    floodFill(a-1, b, NewColor, OldColor);

    floodFill(a, b+1, NewColor, OldColor);

    floodFill(a, b-1, NewColor, OldColor);

示例

// Shows program to fill polygon using floodfill
// algorithm
#include <graphics.h>
#include <stdio.h>
// Describes flood fill algorithm
void flood(int x1, int y1, int new_col, int old_col){
   // Checking current pixel is old_color or not
   if (getpixel(x1, y1) == old_col) {
      // Putting new pixel with new color
      putpixel(x1, y1, new_col);
      // Shows recursive call for bottom pixel fill
      flood(x1 + 1, y1, new_col, old_col);
      //Shows recursive call for top pixel fill
      flood(x1 - 1, y1, new_col, old_col);
      // Shows recursive call for right pixel fill
      flood(x1, y1 + 1, new_col, old_col);
      // Shows recursive call for left pixel fill
      flood(x1, y1 - 1, new_col, old_col);
   }
}
int main(){
   int gd1, gm1 = DETECT;
   // Initializing graph
   initgraph(&gd1, &gm1, "");
   //Shows rectangle coordinate
   int top1, left1, bottom1, right1;
   top1 = left1 = 50;
   bottom1 = right1 = 300;
   // Shows rectangle for print rectangle
   rectangle(left1, top1, right1, bottom1);
   // Fills start cordinate
   int x1 = 51;
   int y1 = 51;
   // Shows new color to fill
   int newcolor = 12;
   // Shows old color which you want to replace
   int oldcolor = 0;
   // Calling for fill rectangle
   flood(x1, y1, newcolor, oldcolor);
   getch();
   return 0;
}

輸出

更新時間:2020 年 7 月 23 日

4 千多人次瀏覽

開啟您的 事業

完成課程,獲得認證

開始
廣告