แนวคิด
เกี่ยวกับสี่เหลี่ยมผืนผ้าที่กำหนด งานคือเติมสีสี่เหลี่ยมผืนผ้านี้โดยใช้อัลกอริทึม flood fill
อินพุต
rectangle(left = 50, top = 50, right = 100, bottom = 100) floodFill(a = 55, b = 55, NewColor = 12, OldColor = 0)
เอาต์พุต

วิธีการ
// ฟังก์ชันเรียกซ้ำเพื่อแทนที่สีเก่า 'OldColor' ที่ '(a, b)' และพิกเซลรอบๆ ของ (a, b) ด้วยสีใหม่ 'NewColor' และ floodFill(a, b, NewColor, OldColor)
- ถ้า a หรือ b อยู่นอกหน้าจอ ให้ return
- ถ้าสีของ 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);
ตัวอย่างโค้ด
#include <graphics.h>
#include <stdio.h>
// อธิบายอัลกอริทึม flood fill
void flood(int x1, int y1, int new_col, int old_col) {
// ตรวจสอบพิกเซลปัจจุบันเป็น old_color หรือไม่
if (getpixel(x1, y1) == old_col) {
// วางพิกเซลใหม่ด้วยสีใหม่
putpixel(x1, y1, new_col);
// เรียกซ้ำสำหรับเติมพิกเซลด้านล่าง
flood(x1 + 1, y1, new_col, old_col);
// เรียกซ้ำสำหรับเติมพิกเซลด้านบน
flood(x1 - 1, y1, new_col, old_col);
// เรียกซ้ำสำหรับเติมพิกเซลด้านขวา
flood(x1, y1 + 1, new_col, old_col);
// เรียกซ้ำสำหรับเติมพิกเซลด้านซ้าย
flood(x1, y1 - 1, new_col, old_col);
}
}
int main() {
int gd1, gm1 = DETECT;
// เริ่มต้นกราฟิก
initgraph(&gd1, &gm1, "");
// พิกัดสี่เหลี่ยมผืนผ้า
int top1, left1, bottom1, right1;
top1 = left1 = 50;
bottom1 = right1 = 300;
// วาดสี่เหลี่ยมผืนผ้า
rectangle(left1, top1, right1, bottom1);
// พิกัดเริ่มต้นเติม
int x1 = 51;
int y1 = 51;
// สีใหม่สำหรับเติม
int newcolor = 12;
// สีเก่าที่ต้องการแทนที่
int oldcolor = 0;
// เรียกเติมสี่เหลี่ยมผืนผ้า
flood(x1, y1, newcolor, oldcolor);
getch();
return 0;
}
ผลลัพธ์
