Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

อัลกอริธึมเติมน้ำท่วมโดยใช้กราฟิก C


แนวคิด

สำหรับสี่เหลี่ยมที่กำหนด งานของเราคือเติมสี่เหลี่ยมนี้โดยใช้อัลกอริธึมเติมน้ำท่วม

ป้อนข้อมูล

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

ผลผลิต

อัลกอริธึมเติมน้ำท่วมโดยใช้กราฟิก C

วิธีการ

// ฟังก์ชันเรียกซ้ำเพื่อแทนที่ 'OldColor' ก่อนหน้าที่ '(a, b)' และพิกเซลโดยรอบทั้งหมดของ (a, b) ด้วยสีใหม่ 'NewColor' และ floodFill (a, b, NewColor, OldColor)

  • หาก a หรือ b อยู่นอกหน้าจอ ให้กลับ

  • หากสีของ getpixel(a, b) เหมือนกับOldColor ดังนั้น

  • ซ้ำสำหรับบน ล่าง ขวา และซ้าย

    เติมน้ำท่วม(a+1, b, NewColor, OldColor);<

    เติมน้ำท่วม(a-1, b, NewColor, OldColor);

    เติมน้ำท่วม(a, b+1, NewColor, OldColor);

    เติมน้ำท่วม(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;
}

ผลลัพธ์

อัลกอริธึมเติมน้ำท่วมโดยใช้กราฟิก C