Write a recursive method that counts the number of creatures on a grid. A creatu
ID: 3760873 • Letter: W
Question
Write a recursive method that counts the number of creatures on a grid. A creature is defined as a contiguous collection of 1's (connected horizontally vertically and diagonally).
Input
Max dimensions of the array
Distribution of organisms on the array
Output
The number of creatures and the layout of the grid showing the locations of the creatures.
Requirements checklist:
Documented source code (include any assumptions you make)
Input File (in.txt)
The format of the input file is as follows: First line is the dimensions of the grid.. Then the grid containing 1s for the creatures and 0s for the spaces. The file terminates by 0 0.
5 5
0 0 0 0 0
0 1 1 1 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
5 5
0 0 0 0 1
0 1 1 1 0
1 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0
Output File (out.txt)
Experiment # 1
Number of Creatures: 1
0 0 0 0 0
0 1 1 1 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Experiment #2
Number of Creatures: 1
0 0 0 0 1
0 1 1 1 0
1 0 0 0 0
0 0 0 0 0
0 0 0 0 0
THE JAVA CODE SHOULD BE SIMMILARE TO THIS CODE
void clearpic(pict parameter, int row, int col)
{
if ((0 <= row) && (row < SIZE) && (0 <= col) && (col < SIZE) && parameter[row][col] == 1)
{
parameter[row][col]=0;
clearpic (parameter,row+1,col);
clearpic (parameter,row,col+1);
clearpic (parameter,row-1,col);
clearpic (parameter,row,col-1);
}
}
Explanation / Answer
public static void clearpic(int[][] a, int row, int col, int SIZE, int count) {
if ((0 <= row) && (row < SIZE) && (0 <= col) && (col < SIZE) && a[row][col] == 1) {
a[row][col] = count;
clearpic(a, row + 1, col, SIZE, count);
clearpic(a, row, col + 1, SIZE, count);
clearpic(a, row - 1, col, SIZE, count);
clearpic(a, row, col - 1, SIZE, count);
}
}
public static void print(int[][] a, int r, int c) {
int count = 1;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
clearpic(a, i, j, a.length, count);
}
count++;
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j]);
}
System.out.print(" ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.