Uva--657 (两重DFS)
2014-07-05 20:36:47
题意&思路:动态的给出DFS范围,再在范围中DFS,即是在DFS再套一层DFS2,(两重DFS)。
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <cstring> 5 using namespace std; 6 int Case = 0,w,h,g[55][55],used[55][55],dot[10005],c,cnt; 7 8 void Dfs2(int x,int y){ 9 if(x < 0 || y < 0 || x >= h || y >= w || g[x][y] != 2 || used[x][y]) 10 return; 11 used[x][y] = 1; 12 Dfs2(x - 1,y); 13 Dfs2(x + 1,y); 14 Dfs2(x,y - 1); 15 Dfs2(x,y + 1); 16 } 17 18 void Dfs(int x,int y){ //draw black 19 if(x < 0 || y < 0 || x >= h || y >= w || g[x][y] == 0 || used[x][y]) 20 return; 21 22 if(g[x][y] == 2){ 23 Dfs2(x,y); 24 ++c; 25 } 26 used[x][y] = 1; 27 Dfs(x - 1,y); 28 Dfs(x,y - 1); 29 Dfs(x,y + 1); 30 Dfs(x + 1,y); 31 } 32 33 int main(){ 34 char str[55]; 35 while(scanf("%d %d",&w,&h) == 2){ 36 if(!w && !h) break; 37 for(int i = 0; i < h; ++i){ 38 scanf("%s",str); 39 for(int j = 0; j < w; ++j){ 40 if(str[j] == '.') g[i][j] = 0; 41 else if(str[j] == '*') g[i][j] = 1; 42 else g[i][j] = 2; 43 } 44 } 45 cnt = 0; 46 memset(used,0,sizeof(used)); 47 for(int i = 0; i < h; ++i){ 48 for(int j = 0; j < w; ++j){ 49 if(!used[i][j] && g[i][j] == 2){ 50 c = 0; 51 Dfs(i,j); 52 dot[cnt++] = c; 53 } 54 } 55 } 56 printf("Throw %d\n",++Case); 57 sort(dot,dot + cnt); 58 printf("%d",dot[0]); 59 for(int i = 1; i < cnt; ++i){ 60 printf(" %d",dot[i]); 61 } 62 printf("\n\n"); 63 } 64 return 0; 65 }