hdu 1241 (Oil Deposits) legendary dfs

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

These days I have encountered some problems when I was doing the searching problems;

May those problem need to use the DFS algorithm!  So I started to learning the DFS:

Lots of friends says this probelm is a simple DFS problem, so I have a try on the problem!

Of course, I learned a lot from the "simple" problem!

hdu 1241 (Oil Deposits) legendary dfs View Code
 1 #include<iostream>

 2 #include<cstring>

 3 #include<queue>

 4 #include<cstdio>

 5 using namespace std;

 6 int mark[111][111];

 7 char map[105][105];

 8 int m,n;

 9 int dir[8][2]={0,1,0,-1,1,0,-1,0,1,-1,-1,1,1,1,-1,-1};

10 void DFS(int a,int b)

11 {

12     int x,y;

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

14     {

15         x=a+dir[i][0];

16         y=b+dir[i][1];

17         if(x>=0&&x<m&&y>=0&&y<n&&mark[x][y]==0&&map[x][y]=='@')

18         {

19             mark[x][y]=1;

20             DFS(x,y);

21         }

22     }

23 }

24 

25 

26 int main()

27 {

28     int i,j;

29     while(cin>>m>>n)

30     {

31         getchar();

32         if(m==0) break;

33         for(i=0;i<m;i++)

34           for(j=0;j<n;j++)

35               cin>>map[i][j];

36         memset(mark,0,sizeof(mark));

37         int sum;

38         sum=0;

39         for(i=0;i<m;i++)

40             for(j=0;j<n;j++)

41             {

42                 if(map[i][j]=='@'&&mark[i][j]==0)

43                 {

44                     sum++;

45                     mark[i][j]=1;

46                     DFS(i,j);

47                 }

48             }

49             cout<<sum<<endl;

50     }

51     return 0;

52 }

 

你可能感兴趣的:(HDU)