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

Write a grid-fill program. Suppose you have a grid that contains randomly placed

ID: 3843993 • Letter: W

Question

Write a grid-fill program. Suppose you have a grid that contains randomly placed 0s and 1s 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 0 to 1, or, select a random cell that contains 1 and flip that cell and all adjacent 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. For example, in the above grid, if you select the highlighted cell that contains a 0, your program should flip that cell and all other adjacent cell that contains 0 to 1, as shown below. The modified cells are shown in bold.

Explanation / Answer

Here you go with the program, change the input however you may like, just remember to change the limit inside the grid function.

import java.util.*;
import java.lang.*;
import java.io.*;

class grid
{
   static void grid(int arr[][], int x, int y, int prev, int newv)
{
   if (x < 0 || x >= 3 || y < 0 || y >= 3) //necessary conditions to move on
       return;
   if (arr[x][y] != prev)
       return;

   arr[x][y] = newv; //chnaging the value from previous to new

//Recursion to top, down, bottom and left
   grid(arr, x+1, y, prev, newv);
   grid(arr, x-1, y, prev, newv);
   grid(arr, x, y+1, prev, newv);
   grid(arr, x, y-1, prev, newv);
}
   public static void main (String[] args)
   {
       int[][] arr=new int[3][3];
       arr[0][0]=0;
       arr[0][1]=1;
       arr[0][2]=0;
       arr[1][0]=1;
       arr[1][1]=0;
       arr[1][2]=0;
       arr[2][0]=0;
       arr[2][1]=1;
       arr[2][2]=0;
       int[] random=new int[2];
       random[0] = (int)Math.round(Math.random()*2);
       random[1] = (int)Math.round(Math.random()*2); //selecting a random value
       for(int i=0;i<3;i++){
           for(int j=0;j<3;j++){
               System.out.print(""+arr[i][j]+" ");
           }
           System.out.println();
       }
       System.out.println(""+random[0]+" "+random[1]);
       if(arr[random[0]][random[1]]==0)grid(arr, random[0], random[1], 0, 1); //if random value is 0 then change to 1
if(arr[random[0]][random[1]]==1)grid(arr, random[0], random[1], 1, 0);
       for(int i=0;i<3;i++){
           for(int j=0;j<3;j++){
               System.out.print(""+arr[i][j]+" ");
           }
           System.out.println();
       }
   }
}

This is a simple recursion problem, let me know if you have any problem !

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote