You are given a 3X3 matrix which has 3 colors ballon Red, Blue and Green.
Consider Red - 1, Blue - 2, Green - 3 in the below matrix. In your program you will pass row and col. Whatever value appears in the matrix for that row and column, that value including its 4 neighbours of the same type (up, left, down, right) should be popped. Now imagine as if gravity is pulling your popped matrix down. After its popped you need to replace the popped value with 0 pull the rows of the matrix to the bottom.
How do you approach this problem?, looks similar to flood fill but the gravity thing is a bit confusing.
Ex: Given matrix:
3 2 3
1 3 1
1 2 2
Lets say you pass row = 1, col = 0. You got value = 1
Step 1:
Step 2:
Now apply gravity on your matrix:
Because you popped (1,0) and (2,0) so column zero will be pulled by gravity. And number 3(0,0) will be pulled at the bottom of the matrix. So your final answer will be
0 2 3
0 3 1
3 2 2
I think I understood till the step 1, after that in step 2 is something where my mind couldn't work, I mean the gravity apparently pulls the 0's to the top and 3 to the bottom, how do you accompalish that!.
So this is finak solution I came up with:
Just an extension of flood fill where your new color would be nothing but 0, which is the number that needs to be replaced.
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
// boolean[][] visited = new boolean[image.length][image[0].length];
if(image[sr][sc] == newColor)
return image;
dfs(image, sr,sc,newColor);
for(int[] i:image){
for(int j:i){
System.out.println("the result is "+j);
}
}
return image;
}
public void dfs(int [][] image, int row, int col, int newColor) {
int temp = image[row][col];
image[row][col] = newColor;
int[] rows = {1,0,-1,0};
int[] cols = {0,1,0,-1};
for(int d = 0; d < 4; d++) {
int newRow = row + rows[d];
int newCol = col + cols[d];
if(newRow >=0 && newRow < image.length && newCol>=0 && newCol < image[0].length && image[newRow][newCol] == temp) {
dfs(image, newRow,newCol, newColor);
}
}
reverseColumn(image);
}
public void reverseColumn(int[][] grid){
System.out.println("in here");
for(int i=0;i<grid.length-1;i++){
for(int j=0;j<grid[0].length-1;j++){
System.out.println(" grid1 "+grid[i+1][j]);
if(grid[i+1][j]==0){
int temp = grid[i+1][j];
grid[i+1][j] = grid[i][j];
grid[i][j] = temp;
}
}
}
}
Let me know if you have anything better!.