java flood fill

Solutions on MaxInterview for java flood fill by the best coders in the world

showing results for - "java flood fill"
Anton
07 Jun 2016
1// Java program to implement flood fill algorithm 
2class GFG 
3{ 
4  
5// Dimentions of paint screen 
6static int M = 8; 
7static int N = 8; 
8  
9// A recursive function to replace previous color 'prevC' at '(x, y)'  
10// and all surrounding pixels of (x, y) with new color 'newC' and 
11static void floodFillUtil(int screen[][], int x, int y,  
12                                    int prevC, int newC) 
13{ 
14    // Base cases 
15    if (x < 0 || x >= M || y < 0 || y >= N) 
16        return; 
17    if (screen[x][y] != prevC) 
18        return; 
19  
20    // Replace the color at (x, y) 
21    screen[x][y] = newC; 
22  
23    // Recur for north, east, south and west 
24    floodFillUtil(screen, x+1, y, prevC, newC); 
25    floodFillUtil(screen, x-1, y, prevC, newC); 
26    floodFillUtil(screen, x, y+1, prevC, newC); 
27    floodFillUtil(screen, x, y-1, prevC, newC); 
28} 
29  
30// It mainly finds the previous color on (x, y) and 
31// calls floodFillUtil() 
32static void floodFill(int screen[][], int x, int y, int newC) 
33{ 
34    int prevC = screen[x][y]; 
35    floodFillUtil(screen, x, y, prevC, newC); 
36} 
37  
38public static void main(String[] args)  
39{ 
40    int screen[][] = {{1, 1, 1, 1, 1, 1, 1, 1}, 
41                    {1, 1, 1, 1, 1, 1, 0, 0}, 
42                    {1, 0, 0, 1, 1, 0, 1, 1}, 
43                    {1, 2, 2, 2, 2, 0, 1, 0}, 
44                    {1, 1, 1, 2, 2, 0, 1, 0}, 
45                    {1, 1, 1, 2, 2, 2, 2, 0}, 
46                    {1, 1, 1, 1, 1, 2, 1, 1}, 
47                    {1, 1, 1, 1, 1, 2, 2, 1}, 
48                    }; 
49    int x = 4, y = 4, newC = 3; 
50    floodFill(screen, x, y, newC); 
51  
52    System.out.println("Updated screen after call to floodFill: "); 
53    for (int i = 0; i < M; i++) 
54    { 
55        for (int j = 0; j < N; j++) 
56        System.out.print(screen[i][j] + " "); 
57        System.out.println(); 
58    } 
59    } 
60} 
61  
62