user3604476
user3604476

Reputation: 5

change the same numbers in a matrix recursively

given a matrix of int numbers, a row and col indexs (for a random cell that contains a number) and a new number, I need to recursively return the matrix- however now with all of the surrounding cells that matched the random cell number to the new one. for example: for the following matrix-

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

called by fill(grid,1,1,0), this one needs to be returned:

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

what I tried is the 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 is a function I'm calling that's checking if both cells have the same number and are next to each other

been stuck on this for a couple of days. would love for some help

Upvotes: 0

Views: 254

Answers (1)

Jason Hu
Jason Hu

Reputation: 6333

If I understand your question correctly, you want to propagate the needed value to neighbors with equal value to origin.

the point here, is to make each node in the grid acts like a automaton, to pass the value to the neighbor if itself gets changed.

following is the code, but i 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
    for (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);
}

Upvotes: 1

Related Questions