/* * Blobcheck. * * csci 210 * * This program counts the size of "blobs" in a 2-D array. The * program uses a recursive function countBlob, which takes as * parameter a grid cell and computes and returns how many cell are * filled around it. The program calls this function for each cell in * the grid. */ public class BlobCheck { //constants to set the values for which the grid is filled or empty private static final char EMPTY = '0'; private static final char FILLED = '1'; private static final char MARKED = '*'; //array to hold the grid of numbers private char grid[][] = { {EMPTY, EMPTY, EMPTY, FILLED, FILLED}, {EMPTY, EMPTY, EMPTY, FILLED, EMPTY}, {FILLED, FILLED, EMPTY, EMPTY, EMPTY}, {FILLED, FILLED, FILLED, EMPTY, FILLED}, {FILLED, FILLED, EMPTY, EMPTY, FILLED} }; //the dimensions of the grid private int nrows, ncols; // The constructor public BlobCheck(){ //set up the grid nrows = grid.length; ncols=grid[0].length; printGrid(); } void printGrid() { System.out.println("The grid is: "); for (int i=0; i< nrows; i++) { for (int j=0; j< ncols; j++) System.out.print( grid[i][j] + " " ); System.out.println(); } } //count blobs in a grid at each position (i, j) public void count() { // call countBlob with all possible locations System.out.println("Blob counts: "); for (int i=0; i= nrows) return 0; if (col < 0 || col >= ncols) return 0; //base case: empty cell if (grid[row][col] != FILLED) return 0; //if we got here, the current grid cell is filled. First mark //it so that the recursive calls don't count it too. Then we //count the blob of the 8 neighbors and we ad them up. Note //that the recursiv calls work on the same grid. Each //recursive call will modify the grid by marking the current //cell. So the blob gets smaller every time Essentially, //that's why the recursion stops. grid[row][col] = MARKED; int blobsize = 1 + countBlob(row-1, col-1) + countBlob(row-1, col) + countBlob(row-1, col+1) + countBlob(row, col-1) + countBlob(row, col+1) + countBlob(row+1, col-1) + countBlob(row+1, col) + countBlob(row+1, col+1); //System.out.println("countBlob i = " + row + ", j= " + col + " :" + blobsize); return blobsize; } void unmarkGrid() { for (int i=0; i< nrows; i++) for (int j=0; j< ncols; j++) if (grid[i][j] == MARKED) grid[i][j] = FILLED; } public static void main(String args[]) { BlobCheck b = new BlobCheck(); b.count(); } }