【暑假集训专题#搜索 HDU1241】

【题目链接】click here~~

【题目大意】'@'代表油田位置,'*'代表地面,八个方向相邻的油田视为一个,求给定地图里油田数目

【解题思路】八个方向搜索即可

代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int N=1010;
int dir4[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
int dir8[8][2]= {{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}};
char mat[N][N];
int row,line,t,k,ans,cnt,res;
bool check(int dx,int dy)
{
    if(dx>=0&&dx<=row&&dy>=0&&dy<=line) return true;
    return false;
}
void dfs(int x,int y)
{
    mat[x][y]='*';
    for(int i=0; i<8; ++i)
    {
        int dx=x+dir8[i][0];
        int dy=y+dir8[i][1];
        if(check(dx,dy)&&mat[dx][dy]=='@')
        {
            dfs(dx,dy);
        }
    }
}
int main()
{
    while(~scanf("%d%d",&row,&line)&&row&&line)
    {
        for(int i=0; i<row; ++i)
            scanf("%s",mat[i]);
        res=0;
        for(int i=0; i<row; ++i)
        {
            for(int j=0; j<line; ++j)
            {
                if(mat[i][j]=='@')
                {
                    dfs(i,j);
                    res++;
                }
            }
        }
        printf("%d\n",res);
    }
    return 0;
}

/*
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@
0 0
*/


你可能感兴趣的:(搜索)