记录

来源:互联网 发布:java 单态模式 编辑:程序博客网 时间:2024/04/29 02:12

图的遍历(搜索与回朔)Oil Deposits

热烈欢迎浙江大学杭航同学(hhanger)莅临杭电交流指导~ 
Oil DepositsTime Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1074    Accepted Submission(s): 585


Problem DescriptionThe 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. 
 
InputThe input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket.
 
OutputFor each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
 
Sample Input1 1*3 5*@*@***@***@*@*1 8@@****@*5 5 ****@*@@*@*@**@@@@*@@@**@0 0  
Sample Output0122 
SourceMid-Central USA 1997 

RecommendEddy

 

首先说明的是他给的数据有问题::即“5 5”后边多了一个空格!!!!

 

代码:利用了广度搜索而且利用了栈

代码

#include<stdio.h>

#include<stack>

#include<string.h>

using namespace std;

char mas[101][101];

int  m,n,fla[101][101],fang[8][2]={1,0,0,1,-1,0,0,-1,1,1,-1,1,1,-1,-1,-1};//对于斜的方向也要搜索!

typedef struct stack1

{

int x;

int y;

}STACK;

stack<STACK> v;

void search(STACK s)

{

int i,j,k;

STACK q;

v.push(s);

fla[s.x][s.y]=1;

while(!v.empty())

{

for(i=0;i<8;++i)

{

q.x=s.x+fang[i][0];//想一下为什么要用一个q,而不直接用s???

q.y=s.y+fang[i][1];

if(fla[q.x][q.y]||q.x<1||q.y<1||q.x>m||q.y>n||mas[q.x][q.y]=='*')////剪枝对于不满足的提前终止

continue;

else

{

v.push(q);

fla[q.x][q.y]=1;

}

}

s=v.top();

v.pop();

}

}

 

void emp()

{

while(!v.empty())

v.pop();

}

int main()

{

int a,b,c,d,i,j,k,tot;

STACK s;

while(scanf("%d%d",&m,&n)&&m)

{

tot=0;

memset(fla,0,sizeof(fla));

getchar();

//putchar(a);

for(i=1;i<=m;++i)

{

for(j=1;j<=n;++j)

{

mas[i][j]=getchar();

//putchar(mas[i][j]);

}

//putchar('\n');

getchar();

}

for(i=1;i<=m;++i)

{

for(j=1;j<=n;++j)

{

if(mas[i][j]=='@'&&!fla[i][j])

{

tot++;

s.x=i;

s.y=j;

search(s);

}

}

}

printf("%d\n",tot);

}

}