In our matrix problem, we don't yet have a nice graph representation. We could build a graph representation from a given matrix and then run the general CC algorithm on it, but it's much easier to directly hardcode the graph structure into the algorithm. That means, instead of having an explicit list of neighbours for each node, we look at the cells around a cell and view them as "neighbours" if they have the same colour. Furthermore, our "numberOfComponents" will have two nested loops to walk over all "nodes". Usually this algorithm is called something like "FloodFill", since we somehow "flood" or "fill" the regions.

This time the code is in Java. The matrix is given as an array of Strings "land". Height and width of the matrix are stored in "m" and "n", respectively.

```  String[] land;
int m, n;
boolean[][] seen;

void flood ( int i, int j, char farmer ) {
if( i<0 || i>=m || j<0 || j>=n || seen[i][j] || land[i].charAt(j)!=farmer )
return;
seen[i][j] = true;
flood( i-1, j, farmer );
flood( i+1, j, farmer );
flood( i, j-1, farmer );
flood( i, j+1, farmer );
}

int numberOfRegions ( String[] land ) {
this.land = land;
m = land.length;
n = land[0].length();
seen = new boolean[m][n];

int answer = 0;
for( int i=0; i<m; ++i ){
for( int j=0; j<n; ++j ){
if( ! seen[i][j] ){
flood( i, j, land[i].charAt(j) );
}
}
}