Flood fill Algorithm | Dimentions of paint screen ; A recursive function to replace previous color ' prevC ' at ' ( x , ▁ y ) ' and all surrounding pixels of ( x , y ) with new color ' newC ' and ; Base cases ; Replace the color at ( x , y ) ; Recur for north , east , south and west ; It mainly finds the previous color on ( x , y ) and calls floodFillUtil ( ) ; Driver Code
M = 8 NEW_LINE N = 8 NEW_LINE def floodFillUtil ( screen , x , y , prevC , newC ) : NEW_LINE INDENT if ( x < 0 or x >= M or y < 0 or y >= N or screen [ x ] [ y ] != prevC or screen [ x ] [ y ] == newC ) : NEW_LINE INDENT return NEW_LINE DEDENT screen [ x ] [ y ] = newC NEW_LINE floodFillUtil ( screen , x + 1 , y , prevC , newC ) NEW_LINE floodFillUtil ( screen , x - 1 , y , prevC , newC ) NEW_LINE floodFillUtil ( screen , x , y + 1 , prevC , newC ) NEW_LINE floodFillUtil ( screen , x , y - 1 , prevC , newC ) NEW_LINE DEDENT def floodFill ( screen , x , y , newC ) : NEW_LINE INDENT prevC = screen [ x ] [ y ] NEW_LINE floodFillUtil ( screen , x , y , prevC , newC ) NEW_LINE DEDENT screen = [ [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 ] , [ 1 , 2 , 2 , 2 , 2 , 0 , 1 , 0 ] , [ 1 , 1 , 1 , 2 , 2 , 0 , 1 , 0 ] , [ 1 , 1 , 1 , 2 , 2 , 2 , 2 , 0 ] , [ 1 , 1 , 1 , 1 , 1 , 2 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 , 2 , 2 , 1 ] ] NEW_LINE x = 4 NEW_LINE y = 4 NEW_LINE newC = 3 NEW_LINE floodFill ( screen , x , y , newC ) NEW_LINE print ( " Updated ▁ screen ▁ after ▁ call ▁ to ▁ floodFill : " ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( screen [ i ] [ j ] , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT