CC-14 : Implement flood fill for image matrix.
Description:
Given an adjacency matrix, implement Floodfill algorithm. Floodfill will start from particular cell containing 1 (oldColor value), and then follow Floodfill path. The Floodfill path can only travel in directions left, right, up down of cells sharing a boundary, but cannot travel diagonal wise. All cells in FLoodfIll path should be set to 3 (newColor value).
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Image Matrix : 1,1,1,1, 2,1,2,2, 2,2,1,2, 2,2,2,1, |
Image Matrix after floodfill : 3,3,3,3, 2,3,2,2, 2,2,1,2, 2,2,2,1, |
| Image Matrix : 1,1,1,1, 2,1,1,2, 2,2,1,2, 2,2,2,1, |
Image Matrix after floodfill : 3,3,3,3, 2,3,3,2, 2,2,3,2, 2,2,2,1, |
Pseudocode:
floodFillImageMatrix (int[][] matrix, int i, int j, int oldColor, int newColor) method:
| While i and j are within index limits of matric and matrix[i][j]==1 and matrix[i][j]==oldColor:
Set matrix[i][j]=newColor.
Recursively call floodFillImageMatrix (matrix, i+1, j, int oldColor, int newColor).
Recursively call floodFillImageMatrix (matrix, i+1, j, int oldColor, int newColor).
Recursively call floodFillImageMatrix (matrix, i+1, j, int oldColor, int newColor).
Recursively call floodFillImageMatrix (matrix, i+1, j, int oldColor, int newColor).
|
Code:
public int[][] floodFillImageMatrix(int[][] matrix, int i, int j, int oldColor, int newColor){
while ((i >= 0 ) && (i < matrix.length)
&& (j >= 0 ) &&(j < matrix[0].length)
&& (matrix[i][j] == oldColor)){
matrix[i][j]=newColor;
floodFillImageMatrix(matrix, i+1, j, oldColor, newColor);
floodFillImageMatrix(matrix, i-1, j, oldColor, newColor);
floodFillImageMatrix(matrix, i, j+1, oldColor, newColor);
floodFillImageMatrix(matrix, i, j-1, oldColor, newColor);
}
return matrix;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |