The technical term for a contiguous pasture in this context is a `component'. A simple way to identify components is by using recursion, specifically a depth first search. Specifically, start with any point in the component, then visit its neighbours, each of which recursively visits its neighbours and so on. As described, this process would never end, but a slight modification makes it very quick. As soon as a cell is visited, it is erased (marked as non-pasture) so that it will not be revisited over and over again. As each cell is erased, a counter for the size of the pasture is increased.
Here is coach Percy Liang's solution:
#include <fstream> #include <iostream> using namespace std; ifstream in("satpix.in"); ofstream out("satpix.out"); char grid[2000][100]; int W, H; int search(int r, int c) { if(r < 0 || c < 0 || r >= H || c >= W || grid[r][c] != '*') return 0; int n = 1; grid[r][c] = '.'; n += search(r+1, c); n += search(r-1, c); n += search(r, c+1); n += search(r, c-1); return n; } int main() { in >> W >> H; for(int r = 0; r < H; r++) in >> grid[r]; int max = 0; for(int r = 0; r < H; r++) { for(int c = 0; c < W; c++) { int p = search(r, c); if(p > max) max = p; } } out << max << endl; return 0; }