问题类型:图,DFS。
03pie’s solution for [UVA-572]:
问题链接
采用两个数组的AC代码:
#include<cstdio>
#include<cstring>
const int maxn=100+5;
char oil[maxn][maxn];
int n,m,idx[maxn][maxn];void dfs(int i,int j,int nub){if(i<0||j>=m||i>=n||j<0) return;if(idx[i][j]>0||oil[i][j]!='@') return;idx[i][j]=nub;for(int ci=-1;ci<=1;ci++)for(int cj=-1;cj<=1;cj++)if(ci!=0||cj!=0) dfs(i+ci,j+cj,nub);
}
int main(){
// freopen("F://inp.txt","r",stdin);while(~scanf("%d%d",&n,&m)&&n&&m){memset(idx,0,sizeof(idx)); for(int i=0;i<n;i++) scanf("%s",oil[i]);int nub=0;for(int i=0;i<n;i++)for(int j=0;j<m;j++)if(idx[i][j]==0&&oil[i][j]=='@')dfs(i,j,++nub);
// for(int i=0;i<n;i++) printf("%s\n",oil[i]);printf("%d\n",nub);}return 0;
}
采用一个数组保存数据的做法,逻辑和判断比较强,AC代码如下:
#include<cstdio>
#include<string>
const int maxn=100+5;
char oil[maxn][maxn];
int n,m;void dfs(int i,int j,char able){if(i<0||j>=m||i>=n||j<0) return;if(oil[i][j]!='@') return;oil[i][j]=able;for(int ci=-1;ci<=1;ci++)for(int cj=-1;cj<=1;cj++)if(ci!=0||cj!=0) dfs(i+ci,j+cj,able);
}
int main(){
// freopen("F://inp.txt","r",stdin);while(~scanf("%d%d",&n,&m)&&n&&m){for(int i=0;i<n;i++) scanf("%s",oil[i]);int ans=0;for(int i=0;i<n;i++)for(int j=0;j<m;j++)if(oil[i][j]=='@'){dfs(i,j,'O');ans++; }
// for(int i=0;i<n;i++) printf("%s\n",oil[i]);printf("%d\n",ans);}return 0;
}
采用一个数组,但却只能过样例,不能AC,BUG在哪里呢?
#include<cstdio>
#include<cstring>
const int maxn=100+5;
char oil[maxn][maxn];
int n,m;void dfs(int i,int j,char able){if(i<0||j>=m||i>=n||j<0) return;if(oil[i][j]!='@') return;oil[i][j]=able;for(int ci=-1;ci<=1;ci++)for(int cj=-1;cj<=1;cj++)if(ci!=0||cj!=0) dfs(i+ci,j+cj,able);
}
int main(){freopen("F://inp.txt","r",stdin);while(~scanf("%d%d",&n,&m)&&n&&m){for(int i=0;i<n;i++) scanf("%s",oil[i]);char able='@';for(int i=0;i<n;i++)for(int j=0;j<m;j++)if(oil[i][j]=='@')dfs(i,j,++able);
// for(int i=0;i<n;i++) printf("%s\n",oil[i]);printf("%d\n",able-'@');}return 0;
}