http://acm.hdu.edu.cn/showproblem.php?pid=5254
#include<iostream> #include<algorithm> #include<string> #include<map> #include<vector> #include<cmath> #include<queue> #include<string.h> #include<stdlib.h> #include<cstdio> #define LL long long #define MP make_pair #define FOR(i,n) for(int i=0;i<(n);++i) using namespace std; typedef long double LD; typedef pair<int, int> PII; typedef pair<PII, int> PIII; typedef pair<LL, LL> PLL; typedef pair<LL, int> PLI; typedef pair<LD, LD> PDD; int vis[505][505]; const int dx[] = {-1,0,1,0}; const int dy[] = {0,1,0,-1}; int main(){ int t; scanf("%d",&t); while(t--){ int n,m; scanf("%d %d",&n,&m); FOR(i,n) FOR(j,m) vis[i][j] = 0; int g; scanf("%d",&g); queue<PII> q; FOR(i,g){ int x,y; scanf("%d %d",&x,&y); vis[x-1][y-1] = 1; q.push(MP(x-1,y-1)); } while(!q.empty()){ PII p = q.front();q.pop(); for(int i = 0;i<4;i++){ int nx = p.first+dx[i]; int ny = p.second+dy[i]; if(nx>=0&&nx<n&&ny>=0&&ny<m&&!vis[nx][ny]){ for(int j=0;j<4;j++){ if(abs(i-j)!=1&&abs(i-j)!=3) //两个1只能是斜对角 continue; int nnx = nx+dx[j]; int nny = ny+dy[j]; if(nnx>=0&&nnx<n&&nny>=0&&nny<m&&vis[nnx][nny]){ vis[nx][ny] = 1; q.push(MP(nx,ny)); break; } } } } } int ans = 0; FOR(i,n) FOR(j,m) if(vis[i][j]) ans++; static int ca = 1; printf("Case #%d:\n%d\n",ca++,ans); } return 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cstdlib> #include<algorithm> #include<cmath> using namespace std; int n,m; int x[502][502]; int vis[502][502]; void dfs(int p,int q){ if(vis[p][q]==1||x[p][q]==1||p<1||p>n||q<1||q>m) return; if(x[p+1][q]==1&&x[p][q+1]==1){ x[p][q]=1; dfs(p-1,q); dfs(p,q-1); } if(x[p+1][q]==1&&x[p][q-1]==1){ x[p][q]=1; dfs(p-1,q); dfs(p,q+1); } if(x[p-1][q]==1&&x[p][q+1]==1){ x[p][q]=1; dfs(p+1,q); dfs(p,q-1); } if(x[p-1][q]==1&&x[p][q-1]==1){ x[p][q]=1; dfs(p+1,q); dfs(p,q+1); } } int main(){ int t; scanf("%d",&t); int cnt=0; while(t--){ scanf("%d %d",&n,&m); memset(x,0,sizeof(x)); memset(vis,0,sizeof(vis)); int p,a,b; scanf("%d",&p); for(int i=0;i<p;++i){ scanf("%d %d",&a,&b); x[a][b]=1; } for(int i=1;i<=n;++i){ for(int j=1;j<=m;++j){ if(vis[i][j]==0&&x[i][j]==0) dfs(i,j); } } int s=0; for(int i=1;i<=n;++i){ for(int j=1;j<=m;++j){ if(x[i][j]==1) s++; } } printf("Case #%d:\n",++cnt); printf("%d\n",s); } return 0; }