Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Grid-Fill write a grid-fill program. Suppose you have a grid that contains rando

ID: 3844169 • Letter: G

Question

Grid-Fill write a grid-fill program. Suppose you have a grid that contains randomly placed os and 1 as shown below. You should write a program that allows you to select a random cell that contains a 0 and flip that cell and all other adjacent cluster of cells that have o to 1, or select a random cell that contains and flip that cell and all cluster of cells that contain 1 to 0. To select the adjacent cell, consider neighbors in the left, right, top, and down directions only. You need not consider neighboring cells along the diagonals. 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 1 0 0 1 1 0 0 1 1 1 0 0 1 01 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 0 0 1 0 1 1 1 1 0 0 0 1 0 0 0 0 1 0 01 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 L0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 1 0 0 0 0 0 0

Explanation / Answer

import java.util.Random;

public class grid_fill {
  
public static void main(String args[]){
  
//consider the grid of 100X100
int grid[][]=new int[10][10],rows=10,col=10,i,j;
Random rand =new Random();
  
//Initializing the grid
for(i=0;i<rows;i++)
for(j=0;j<col;j++)
grid[i][j]=rand.nextInt(2);

//to display the grid
for(i=0;i<rows;i++){
for(j=0;j<col;j++){
System.out.print(grid[i][j]+" ");
}
System.out.println();
}

//to select a random cell
i=rand.nextInt(rows); // random row
j=rand.nextInt(col); // random col
//to display the randomly selected cell
System.out.println("Selected cell is" +i+","+j);


int value=grid[i][j];// value of the randomly selected cell
int flip_value;// to set the value after flipping the cell

//if value=0, then flip_value=1
//if value=1, then flip_value=0

if(value==0)
flip_value=1;
else
flip_value=0;

//to flip the cells as given in the question
  

grid[i][j]=flip_value; //set the value of the cell to flip_value

//left cell is grid[i][j-1] and for leftmost cell j=0
//if left cell contains the same value as the cell then flip it
if(j-1>=0&&grid[i][j-1]==value)
grid[i][j-1]=flip_value;

  
//right cell is grid[i][j+1] and for rightmost cell j=col-1
//if right cell contains the same value as the cell then flip it
if(j+1<col&&grid[i][j+1]==value)
grid[i][j+1]=flip_value;

//top cell is grid[i-1][j] and for topmost cell i=0
//if top cell contains the same value as the cell then flip it
if(i-1>=0&&grid[i-1][j]==value)
grid[i-1][j]=flip_value;

//bottom cell is grid[i+1][j] and for bottommost cell i=rows-1
//if bottom cell contains the same value as the cell then flip it
if(i+1<rows&&grid[i+1][j]==value)
grid[i+1][j]=flip_value;


//to display the flipped grid
for(i=0;i<rows;i++){
for(j=0;j<col;j++){
System.out.print(grid[i][j]+" ");
}
System.out.println();
}



}


  
  
  
  
  
}