二Day1 F - Oil Deposits

F - Oil Deposits


题目正文

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
The 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.
Output
For 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 Input
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@
@
@@**@
0 0
Sample Output
0
1
2
2

题意

主要是判断@连在一起的有多少种

代码

代码:

//1.定义一个二维数组,mark[101][101]={0},dx[]={-1,},dy[]={}定义一个m,n,ans=0;
//2.search(),传入三个参数,x,y,id,if语句判断一个是否出界,if语句判断mark[x][y]是否大于零,if判断
//或是否等于@符号,mark[x][y]赋值,for循环递归调用,search(x+dx[i],,,id);
//3.主函数,while循环,ans=0清零,初始化mark  memset(mark,0,sizeof(mark))
//4.循环输入要测试的数,map[i],双层循环输入,mark[i][j]是否等于零是否等于@
//5.调用search,最后输出ans,n=0;
#include<stdio.h>
#include<cstring>
#include<iostream>
using namespace std;
char map[100][100];
int mark[101][101]={
    
    0},
dx[]={
    
    -1,-1,-1,0,0,1,1,1},
dy[]={
    
    -1,0,1,-1,1,-1,0,1};
int a=0,b=0,ans;
void search(int x,int y,int z)
{
    
    
    if(x<0 || x>=a || y<0 || y>=b)return ;
    if(mark[x][y]>0 || map[x][y]!='@')return ;
    mark[x][y]=z;
    for(int i=0;i<=7;i++)
        search(x+dx[i],y+dy[i],z);
}
int main()
{
    
    

    while(scanf("%d%d",&a,&b)&& a!=0)
    {
    
    
         ans=0;
         memset(mark,0,sizeof(mark));
         for(int i=0;i<a;i++)
            scanf("%s",map[i]);
         for(int i=0;i<a;i++)
         {
    
    
             for(int j=0;j<b;j++)
             {
    
    
                 if((mark[i][j]==0) && (map[i][j]=='@'))
                    search(i,j,++ans);
             }
         }
         cout<<ans<<endl;
         b=0;
    }
    return 0;
}

总结

递归调用dfs()

猜你喜欢

转载自blog.csdn.net/MarigoldLi/article/details/119454300