POJ1562,Oil Deposits,dfs+bfs,這幾天有做東西,沒寫部落格= =
阿新 • • 發佈:2019-02-11
Oil Deposits
Description
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.Input
Output
Sample Input
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
Sample Output
0 1 2 2
分析:
題目不難,主要用來熟悉深搜廣搜...
code:
//廣搜 #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> #define MAX 100 using namespace std; char region[MAX+5][MAX+5]; int vis[MAX+5][MAX+5]; typedef struct node { int i,j; }node; node que[MAX+5]; void bfs(int i,int j,int m,int n) { int front=0,rear=1,tmpi,tmpj,a,b; que[0].i=i; que[0].j=j; vis[i][j]=1; while(front<rear) { front++; for(a=-1;a<2;a++) for(b=-1;b<2;b++) { tmpi=que[front-1].i+a; tmpj=que[front-1].j+b; if(!a&&!b) continue; if(region[tmpi][tmpj]=='@'&&tmpi<m&&tmpi>=0&&tmpj<n&&tmpj>=0&&!vis[tmpi][tmpj]) { que[rear].i=tmpi; que[rear].j=tmpj; rear++; vis[tmpi][tmpj]=1; } } } } int main() { freopen("input.txt","r",stdin); int m,n,i,j,pocket=0; while(scanf("%d %d",&m,&n),m||n) { memset(region,'*',sizeof(region)); memset(vis,0,sizeof(vis)); pocket=0; for(i=0;i<m;i++) scanf("%s",region+i); for(i=0;i<m;i++) for(j=0;j<n;j++) if(region[i][j]=='@'&&!vis[i][j]) { pocket++; bfs(i,j,m,n); } printf("%d\n",pocket); } return 0; }
//深搜
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define MAX 100
using namespace std;
char region[MAX+5][MAX+5];
int vis[MAX+5][MAX+5];
void dfs(int x,int y)
{
if(region[x][y]=='*'||vis[x][y]) return;
vis[x][y]=1;
dfs(x-1,y-1);dfs(x-1,y);dfs(x-1,y+1);
dfs(x,y-1); dfs(x,y+1);
dfs(x+1,y-1);dfs(x+1,y);dfs(x+1,y+1);
}
int main()
{
int m,n,i,j,pocket=0;
char s[MAX+5];
while(scanf("%d %d",&m,&n),m||n)
{
memset(region,'*',sizeof(region));
memset(vis,0,sizeof(vis));
pocket=0;
for(i=0;i<m;i++)
{
scanf("%s",s);
for(j=0;j<n;j++)
region[i+1][j+1]=s[j];
}
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
if(!vis[i][j]&®ion[i][j]=='@')
{
pocket++;
dfs(i,j);
}
printf("%d\n",pocket);
}
return 0;
}