flood fill
#include<stdio.h>
#include<stdlib.h>
#define N 410
int g[N][N], st[N][N];
int ans[N * N / 2 + 1], idx;
int qx[N * N], qy[N * N], hh, tt = -1;
int n, m;
int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
int cmp(const void *a, const void *b){
return *(int*)a - *(int*)b;
}
int bfs(int x, int y){
++ tt;
qx[tt] = x, qy[tt] = y;
st[x][y] = 1;
int start = hh;
while(hh <= tt){
int a = qx[hh], b = qy[hh];
hh ++;
for(int i = 0; i < 4; i ++){
int nx = a + dx[i], ny = b + dy[i];
if(nx < 0 || ny < 0 || nx >= n || ny >= m || g[nx][ny] == 0 || st[nx][ny]) continue;
st[nx][ny] = 1;
++ tt;
qx[tt] = nx, qy[tt] = ny;
}
}
return tt - start + 1;
}
int main(){
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++)
for(int j = 0; j < m; j ++)
scanf("%d", &g[i][j]);
for(int i = 0; i < n; i ++)
for(int j = 0; j < m; j ++)
if(g[i][j] && !st[i][j]){
int res = bfs(i, j);
if(res) ans[idx ++] = res;
}
qsort(ans, idx, sizeof(int), cmp);
for(int i = idx - 1; i >= 0; i --) printf("%d
", ans[i]);
return 0;
}