Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.hdu.edu.cn/showproblem.php?pid=2258

DFS

我的代码
 1 #include <stdio.h>
2 #include <string.h>
3 const int N=25;
4 const int dx[4]={0,1,0,-1};
5 const int dy[4]={1,0,-1,0};
6 char maze[N][N];
7 bool vis[N][N];
8 int m,n,cnt;
9 void dfs1(int x,int y,char c)
10 {
11 vis[x][y]=1; cnt++;
12 int d,nx,ny;
13 for (d=0;d<4;d++)
14 {
15 nx=x+dx[d]; ny=y+dy[d];
16 if (maze[nx][ny]==c && !vis[nx][ny]) dfs1(nx,ny,c);
17 }
18 }
19 void dfs2(int x,int y,char c)
20 {
21 maze[x][y]=0;
22 int d,nx,ny;
23 for (d=0;d<4;d++)
24 {
25 nx=x+dx[d]; ny=y+dy[d];
26 if (maze[nx][ny]==c) dfs2(nx,ny,c);
27 }
28 }
29 int main()
30 {
31 int mc,mx,my,ans,i,j;
32 while (~scanf("%d%d",&n,&m))
33 {
34 ans=0;
35 memset(maze,0,sizeof(maze));
36 for (i=1;i<=n;i++) scanf("%s",maze[i]+1);
37 for (i=1;i<=n;i++) for (j=1;j<=m;j++)
38 if (maze[i][j]=='0') maze[i][j]=0;
39 while (1)
40 {
41 mc=0;
42 memset(vis,0,sizeof(vis));
43 for (i=1;i<=n;i++)
44 for (j=1;j<=m;j++) if (maze[i][j] && !vis[i][j])
45 {
46 cnt=0;
47 dfs1(i,j,maze[i][j]);
48 if (cnt>mc) {mc=cnt; mx=i; my=j;}
49 }
50 if (mc<2) break;
51 ans+=mc*(mc-1);
52 dfs2(mx,my,maze[mx][my]);
53 for (j=1;j<=m;j++)
54 {
55 int k,flag=0;
56 if (maze[n][j]) flag=1;
57 for (i=n-1;i>0;i--) if (maze[i][j])
58 {
59 flag=1; k=i;
60 while (k<n && maze[k+1][j]==0)
61 {
62 maze[k+1][j]=maze[k][j];
63 maze[k][j]=0;
64 k++;
65 }
66 }
67 if (flag)continue;
68 for (i=1;i<=n;i++)
69 for (k=j;k>0;k--) maze[i][k]=maze[i][k-1];
70 }
71 }
72 printf("%d\n",ans);
73 }
74 return 0;
75 }

 

posted on 2012-01-15 18:59  Qiuqiqiu  阅读(243)  评论(0编辑  收藏  举报