Probably belongs on codereview, not stack overflow. Some minor points to help... Use a queue instead of recursion. The queue can be held as a plain array and you maintain a head and tail pointer or index. Avoid the use of 2D indices. Multiplication is a cost. You can store the position as just a pointer or a 1D index, and use offsets from there (-W, -1, 1, W). Consider some branchless code for both counting and queuing, then measure it.
e.g. int *n = p-W; count += (*n==0); *tail = n; tail += (*n == *p);
-- where
p
points to the current stone having its neighbours tested. —
paddy just now