POJ1979

摘要:BFS

 

#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;

const int size = 20;
int input[size+1][size+1] = {0};
int flag[size+1][size+1] = {0};
int sum = 0;

struct Pos{
    int x;
    int y;
};

Pos getNextPos(Pos cur, int dir)
{
    Pos next;
    if( dir == 1){
        next.x = cur.x;
        next.y = cur.y-1;
    }
    if( dir == 2){
        next.x = cur.x+1;
        next.y = cur.y;
    }
    if( dir == 3 ){
        next.x = cur.x;
        next.y = cur.y+1;
    }
    if( dir == 4 ){
        next.x = cur.x-1;
        next.y = cur.y;
    }
    
    return next;
}

int main()
{
    int W, H;
    while( cin >> W >> H ){
        if( W== 0 ){
            break;    
        }
        char ch;
        Pos start;
        for(int i=1; i<=H; i++){
            for(int j=1; j<=W; j++){
                cin >> ch;
                input[i][j] = (ch=='#'?0:1);
                flag[i][j] = 1;
                if(ch == '@'){
                    start.x = j;
                    start.y = i;
                }            
            }
        }
        
        queue<Pos> q;
        q.push(start);
        flag[start.y][start.x] = 0;
        sum = 1;    
        while( !q.empty() ){
            Pos cur_pos = q.front();
            q.pop();
            
            for(int i=1; i<=4; i++){
                Pos next_pos = getNextPos(cur_pos, i);
                if( next_pos.x<1 || next_pos.x>W || next_pos.y<1 || next_pos.y>H ){
                    continue;
                }
                if( input[next_pos.y][next_pos.x]==0 || flag[next_pos.y][next_pos.x]==0){
                    continue;    
                }    
                sum++;
                q.push(next_pos);
                flag[next_pos.y][next_pos.x] = 0;
            }                                            
        }
        
        cout << sum << endl;
    }

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值