Computer graphics program to implement Flood fill algorithm

0
793

Computer graphics program in Python graphics.py and C++ graphics

Python

#EXPERIMENT 7.1 - FLOODFILL
def isValid(input, m, n, x, y, prev_color, new_color):
   if (x<0 or x>= m) or (y<0 or y>= n) or (input[x][y]!= prev_color) or (input[x][y]== new_color):
       return False
   return True
  
def floodfill(screen,   m, n, x,   y, prevC, newC):
   queue = []
   
   queue.append([x, y])
    screen[x][y] = newC
    while queue:
         
       currPixel = queue.pop()
        
       po-sX = currPixel[0]
       posY = currPixel[1]
         
       if isValid(screen, m, n,  
               posX + 1, posY,  
                       prevC, newC):
             
           screen[posX + 1][posY] = newC
           queue.append([posX + 1, posY])
        
       if isValid(screen, m, n,  
                   posX-1, posY,  
                       prevC, newC):
           screen[posX-1][posY]= newC
           queue.append([posX-1, posY])
        
       if isValid(screen, m, n,  
               posX, posY + 1,  
                       prevC, newC):
           screen[posX][posY + 1]= newC
           queue.append([posX, posY + 1])
        
       if isValid(screen, m, n,  
                   posX, posY-1,  
                       prevC, newC):
           screen[posX][posY-1]= newC
           queue.append([posX, posY-1])
 
 
row = int(input("Enter the number of rows -"))
col = int(input("Enter the number of columns-"))
 
val = []
print("Enter the values:")
 for i in range(row):         
   temp =[]
   for j in range(col):
        x=int(input())
        temp.append(x)
   val.append(temp)
 
 
x = int(input("Enter the x-coordinate of the pixel-"))
y = int(input("Enter the y-coordinate of the pixel-"))
 
prev_color = val[x][y]
 
new_color = int((input("Enter the value of the new color-")))
 floodfill(val, row, col, x, y, prev_color, new_color)
 
for i in range(row):
   for j in range(col):
       print(val[i][j], end =' ')
   print()
Computer graphics program to implement Flood fill algorithm

C++

#include <bits/stdc++.h>
#include <graphics.h>
using namespace std;
 
void floodfillalgo(int x, int y, int color)
{
    if (getpixel(x, y) == color)
    {
        putpixel(x, y, 5);
        floodfillalgo(x + 1, y, color);
        floodfillalgo(x - 1, y, color);
        floodfillalgo(x, y + 1, color);
        floodfillalgo(x, y - 1, color);
    }
    else return;
}
 
int main()
{
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "");
    rectangle(100, 100, 200, 200);
    floodfillalgo(110, 110, getpixel(110, 110));
    getch();
    closegraph();
 
    return 0;
}
 
Computer graphics program to implement Flood fill algorithm

LEAVE A REPLY