题目网址 https://onlinejudge.org/external/5/p572.pdf
题意翻译
【题目大意】输入多个m行n列的矩阵,用00表示输入结束。找出有多少块石油区域,用“@”代表石油,假如两个“@”在横,竖或对角线上相邻,就说它们位于同一区域,对于每个输入,输出一个数表示有几个石油区域。
输入 #1
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@
0 0
输出 #1
0
1
2
2
然后直接看吧
#include "iostream" #include "algorithm" #include "cmath" #include "cstdio" #include "cstring" #include "queue" #include "vector" using namespace std; inline int read(){ int chtholly=0,willem=1;char c=getchar(); while(c<'0' || c>'9'){if(c=='-')willem=-1;c=getchar();} while(c<='9' && c>='0'){chtholly=chtholly*10+(int)(c-'0');c=getchar();} return chtholly*willem; } int gox[9]={0,0,0,1,1,1,-1,-1,-1}; int goy[9]={0,1,-1,0,1,-1,0,1,-1}; //定义搜索方向 bool f[110][110];//f[i][j]用于判断oil[i][j]是否已经搜过 char oil[110][110]; int m,n,ans; void dfs(int x,int y){ // if(f[x][y]==1) return;//貌似并不需要这一句 f[x][y]=1;//标记 for(int i=1;i<=8;i++){ if(oil[x+gox[i]][y+goy[i]]=='@'&&f[x+gox[i]][y+goy[i]]==0) dfs(x+gox[i],y+goy[i]);//移动 } //搜索 } int main(){ while(1){ memset(oil,'*',12100); memset(f,0,12100); ans=0; //初始化 n=read();m=read(); if(n==0) return 0; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){ cin>>oil[i][j]; } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){ if(f[i][j]==1||oil[i][j]=='*') continue; //此区域是之前搜过的了 else{ ans+=1; //因为每一次这里的搜索都是面向一个新的区域, //所以ans直接加一就可以了 dfs(i,j); } } cout<<ans<<endl; } //没了 }