hdu 1241 Oil Deposits 简单八个方向的DFS

http://acm.hdu.edu.cn/showproblem.php?pid=1241

给一个二维图

*:缺乏油的地方;

@:有油的地方;

当@与@之间相邻(水平,垂直,对角线八个方向都可),算同一个油田。求最多有多少个油田;

#include <stdio.h>
#include <string.h>
#include<stdlib.h>
#include <cmath>
#include <iostream>
using namespace std;
#define MAXSIZE 103
int dir[8][3]={{1,0},{-1,0},{0,-1},{0,1},{1,1},{-1,-1},{-1,1},{1,-1}},ro,co;
char map[MAXSIZE][MAXSIZE];
bool judge(int a,int b)
{
     if(a<0||b<0||a>=ro||b>=co)
      return false;
     if(map[a][b]!='@')
      return false;
     return true;
}
void dfs(int a,int b)
{
   int a1,b1,i;
    for(i=0;i<8;i++)
    {
         a1=a+dir[i][0];
         b1=b+dir[i][1];
         if(!judge(a1,b1))
            continue;
         map[a1][b1]='*';
         dfs(a1,b1);
    }
}  
int main()
{
      int i,j,ans,x;
      while(scanf("%d%d",&ro,&co),ro||co)
      {
        ans=0;
        for(i=0;i<ro;i++)
        cin>>map[i];
        for(i=0;i<ro;i++)
        for(j=0;j<co;j++)
        {
          if(map[i][j]=='@')
          { ans++;
            map[i][j]='*';
            dfs(i,j);
          }
        }
        printf("%d\n",ans);
     }
     return 0;
}
           

原文地址:https://www.cnblogs.com/zxj015/p/2740269.html