hdu 1312 Red and Black(DFS)

题目: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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值