java - change the same numbers in a matrix recursively -


given matrix of int numbers, row , col indexs (for random cell contains number) , new number, need recursively return matrix- of surrounding cells matched random cell number new one. example: following matrix-

             4,1,2,2              4,4,3,1              1,4,4,4              1,4,0,2 

called fill(grid,1,1,0), 1 needs returned:

 * 0    1   2   2    0    0   3   1    1    0   0   0    1    0   0   2 

what tried following

public static int[][] fill(int[][] grid, int i, int j, int needed ) {      if (i<= grid.length - 1 && j<=grid[0].length - 1 && i>0 && j>0) {     grid[i][j] = needed ;      if(legal_neighbor(grid,i,j, i+1,j))         grid= fill(grid, i+1,j,needed );     if(legal_neighbor(grid,i,j, i,j+1))         grid= fill(grid, i,j+1,needed );     if(legal_neighbor(grid,i,j, i,j-1))         grid= fill(grid, i,j-1,needed );     if(legal_neighbor(grid,i,j, i-1, j))         grid= fill(grid, i-1,j,needed );      } 

where legal_neighbor function i'm calling that's checking if both cells have same number , next each other

been stuck on couple of days. love help

if understand question correctly, want propagate needed value neighbors equal value origin.

the point here, make each node in grid acts automaton, pass value neighbor if gets changed.

following code, left boundarycheck blank:

static int[][] fill(int[][] grid, int i, int j, int needed) {     if (!boundarycheck()) throw new runtimeexception();     int[][] clone = new int[grid.length][grid[0].length];     //clone matrix grid     (int k = 0; k < clone.length; k++) {         clone[k] = grid[k].clone();     }     propagate(clone, i, j, needed, grid[i][j]);     return clone; }  static void propagate(int[][] grid, int i, int j, int needed, int target) {     if (!boundarycheck() || grid[i][j] != target || needed == target) return;     grid[i][j] = needed;     propagate(grid, i+1, j, needed, target);     propagate(grid, i-1, j, needed, target);     propagate(grid, i, j+1, needed, target);     propagate(grid, i, j-1, needed, target); } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -