Java Reference
In-Depth Information
printOrg(out, G, m, n);
in.close(); out.close();
} // end main
public static void findOrg(int[][] G, int i, int j, int m, int n) {
if (i < 0 || i >= m || j < 0 || j >= n) return; //outside of grid
if (G[i][j] == 0 || G[i][j] > 1) return; //no cell or cell already seen
// else G[i][j] = 1;
G[i][j]= orgCount + 1; //so that this 1 is not considered again
findOrg(G, i - 1, j, m, n); //North
findOrg(G, i, j + 1, m, n); //East
findOrg(G, i + 1, j, m, n); //South
findOrg(G, i, j - 1, m, n); //West
} //end findOrg
public static void printOrg(PrintWriter out, int[][] G, int m, int n) {
out.printf("\nNumber of organisms = %d\n", orgCount);
out.printf("\nPosition of organisms are shown below\n\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
if (G[i][j] > 1) out.printf("%2d ", G[i][j] - 1);
//organism labels are one more than they should be
else out.printf("%2d ", G[i][j]);
out.printf("\n");
}
} //end printOrg
} //end class Organisms
If the file orgs.in contains the following:
5 7
0 1 0 1 1 1 0
0 0 1 1 0 0 0
1 1 0 1 0 0 1
1 0 1 0 0 1 1
1 1 0 0 0 1 0
then Program P5.2 produces the following output in the file orgs.out :
Number of organisms = 5
Position of organisms are shown below
0 1 0 2 2 2 0
0 0 2 2 0 0 0
3 3 0 2 0 0 4
3 0 5 0 0 4 4
3 3 0 0 0 4 0
Search WWH ::




Custom Search