您的位置:首页 > 其它

hdu 1312 Red and Black(DFS)

2015-08-06 22:22 302 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1312

大意:一个人只能在'.'上移动,问@所在地的人能到多少个'.'。

Sample Input

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0




Sample Output

45
59
6
13


在输入字符数组时候要么用不出错的cin,要么用这样的格式:

getchar();

for(i=1;i<=h;i++)

{

for(j=1;j<=w;j++)

{

scanf("%c",&a[i][j]);

}

getchar();

}

不要用这样的格式:

for(i=1;i<=h;i++)

{

getchar();

for(j=1;j<=w;j++)

{

scanf("%c",&a[i][j]);

}

}

有时这会出错。

来看看两种风格的DFS:

(1):

#include <iostream>
#include<cstdio>
using namespace std;
char s[25][25];
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int ans=0;
int lie,hang;
void dfs(int x,int y){
    s[x][y]='#';
    ans++;
    for(int i=0;i<4;i++){
        int tx=x+dir[i][0],ty=y+dir[i][1];
        if(tx<hang&&tx>=0&&ty<lie&&ty>=0&&s[tx][ty]=='.'){
             dfs(tx,ty);
        }
    }
}
int main()
{
    //freopen("cin.txt","r",stdin);
    while(cin>>lie>>hang){
        if(lie==0&&hang==0)break;
        int x,y;
        ans=0;
        for(int i=0;i<hang;i++){
            getchar();
            for(int j=0;j<lie;j++){
                scanf("%c",&s[i][j]);
                if(s[i][j]=='@'){  x=i; y=j; }
            }
        }
        dfs(x,y);
        printf("%d\n",ans);
    }
    return 0;
}


(2):

#include <iostream>
#include<cstdio>
using namespace std;
char a[25][25];
int w,h;
int f(int i,int j)
{
     if(i<1||i>h||j<1||j>w) return 0;
     if(a[i][j]!='#')
     {
          a[i][j]='#';
          return 1+f(i-1,j)+f(i+1,j)+f(i,j+1)+f(i,j-1);
     }
     else return 0;
}
int main()
{
    //freopen("cin.txt","r",stdin);
    int i,j;
    while(~scanf("%d%d",&w,&h)&&w&&h)
    {
        int x,y;
        getchar();
         for(i=1;i<=h;i++)
         {
              for(j=1;j<=w;j++)
              {
                   scanf("%c",&a[i][j]);
                   if(a[i][j]=='@'){  x=i; y=j; }
              }
              getchar();
         }
         printf("%d\n",f(x,y));
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: