Please do it on java programming Write a recursive method that counts the number
ID: 3544966 • Letter: P
Question
Please do it on java programming
Write a recursive method that counts the number of creatures on a grid. An creature is defined as a contiguous collection of 1's (connected horizontally and vertically).
Max dimensions of the array
Distribution of organisms on the array
The number of creatures and the layout of the grid showing the locations of the creatures.
Requirements checklist:
q 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: 3
0 0 0 0 1
0 2 2 2 0
3 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CreatureCounter {
public static void fill(int grid[][], int i, int j, int fillValue) {
if (grid[i][j] != -1) return;
grid[i][j] = fillValue;
if (i > 0) fill(grid, i-1, j , fillValue);
if (j > 0) fill(grid, i , j-1, fillValue);
if (i+1 < grid.length) fill(grid, i+1, j , fillValue);
if (j+1 < grid[0].length) fill(grid, i , j+1, fillValue);
}
public static void main(String[] args) {
try {
// Open input file
Scanner fileIn = new Scanner(new File("in.txt"));
int experimentCounter = 0;
//Open output file
PrintWriter fileOut = new PrintWriter("out.txt");
while (true) {
// Read dimensions
int row = fileIn.nextInt();
int col = fileIn.nextInt();
if (row == 0 && col == 0) break;
++experimentCounter;
int [][] grid = new int[row][col];
// Read grid
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
grid[i][j] = fileIn.nextInt();
if (grid[i][j] == 1) grid[i][j] = -1;
}
}
// Count creatures
int creatureCounter = 0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (grid[i][j] == -1) fill(grid, i, j, ++creatureCounter);
}
}
// Output result to file
fileOut.printf("Experiment # %d ", experimentCounter);
fileOut.printf("Number of Creatures: %d ", creatureCounter);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
fileOut.printf("%d ", grid[i][j]);
}
fileOut.println();
}
}
// Close input and output files
fileIn.close();
fileOut.close();
} catch (FileNotFoundException ex) {
System.out.println("Input file not found.");
}
}
}