Java Consider an N N grid in which some squares are occupie
*Java*
Consider an N × N grid in which some squares are occupied. Two squares belong to the same group if they share a common edge. In Figure 7.30 there is one group of four occupied squares, three groups of two occupied squares, and two individual occupied squares. Assume that the grid is represented by a two-dimensional array. Write a program that
a. Computes the size of a group when a square in the group is given
Solution
public class calculateGroup {
public int count = 0;
public int size = 5;
public String[][] strArr = new String[size][size];
public void fillArr(){
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
strArr[i][j] = \"notVisited\";
}
}
}
//recursively calculating neighbours
public int calculateGroupLength(int arr[][], int posX, int posY){
if(posX >= 0 && posY <= size && arr[posX][posY] == 1 && strArr[posX][posY] == \"notVisited\"){
count++;
strArr[posX][posY] = \"visited\";
}
else{
return 0;
}
calculateGroupLength(arr,posX,posY+1);
calculateGroupLength(arr,posX,posY-1);
calculateGroupLength(arr,posX+1,posY-1);
calculateGroupLength(arr,posX+1,posY);
calculateGroupLength(arr,posX+1,posY+1);
calculateGroupLength(arr,posX-1,posY-1);
calculateGroupLength(arr,posX-1,posY);
calculateGroupLength(arr,posX-1,posY+1);
return 0;
}
public int returnCount(){
return count;
}
//main
public static void main(String args[]){
int arr[][]={{0,1,1},{0,0,1},{1,1,1}};
calculateGroup obj = new calculateGroup();
obj.fillArr();
//calculating neighbours
obj.calculateGroupLength(arr,1,1);
System.out.println(\"Total group length: \"+obj.returnCount());
}
}
