首页 > 代码库 > hdu 1312 DFS算法简单题

hdu 1312 DFS算法简单题

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1312

此题与油田那题很像是练习深搜的好题,题意是从“@”开始,遍历整个图,找到连接的 “.”有多少个

但要考虑变化,简单处理下就行了,主要是斜角的不要了,而且判断结束方式也不一样

具体看代码吧

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
char map[25][25];
int n,m;
int count;
int dir[4][2]={ 0,1, 1,0  ,0,-1,-1,0 };
void dfs(int x,int y)
{
    int xx=x;
    int yy=y;
    map[x][y]=‘#‘;
    count++;
    //  map[x][y]=‘#‘;
    for(int i=0;i<4;i++)
    {
        xx=x+dir[i][0];
        yy=y+dir[i][1];
        if(xx<0 || yy<0 || xx>=m || yy>=n || map[xx][yy]==‘#‘)
        {
                continue;
        }
        //  printf("%d%d^^",xx,yy);
        dfs(xx,yy);
    }  
}
 
int main()
{
    int i,j;
    while(scanf("%d%d",&n,&m)!=EOF&&n||m)
    {
            getchar();
            for(i=0;i<m;i++)
            {
                    for(j=0;j<n;j++)
                    {
                            scanf("%c",&map[i][j]);
                    }
                    getchar();
            }
            int x,y;
            count=0;
            for(i=0;i<m;i++)
                for(j=0;j<n;j++)
                {
                        if(map[i][j]==‘@‘)
                        {
                            x=i;y=j;   
                        }
                }
            dfs(x,y);
            printf("%d\n",count);
    }
}