HDU 1312 Red and Black

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1312
题记:用广度优先搜索和队列的方式把所有格子走一步。

#include<bits/stdc++.h>

using namespace std;

#define check(x,y)(x<wx&&x>=0&&y>=0&&y<hy)//判断是否在room中

char room[25][25];

int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};
//左上角坐标为(0,0),向左,向上,向右,向下

int wx,hy,num;

struct node{
    int x,y;
};

void bfs(int dx,int dy){
    num=1;//起点图块也算一个
    queue<node>q;
    node start,next;
    start.x=dx;
    start.y=dy;
    q.push(start);//起点入队
    while(!q.empty()){//当队列不为空时
        start=q.front();//返回队首元素
        q.pop();//删除队首元素
        //cout<<"out"<<start.x<<start.y<<endl;(打印出队列情况,用于验证)
        for(int i=0;i<4;i++){//四个方向逐一搜索
            next.x=start.x+dir[i][0];
            next.y=start.y+dir[i][1];
            if(check(next.x,next.y)&&room[next.x][next.y]=='.'){
                //判断当前位置是否在room中且是黑色图块(即'.')
                room[next.x][next.y]='#';//入队后标记已经处理过
                num++;//黑色图块加一
                q.push(next);//进队
            }
        }
    }
}

int main(){
    int x,y,dx,dy;
    while(cin>>wx>>hy){
        if(wx==0&&hy==0)
            break;
        for(y=0;y<hy;y++){
            for(x=0;x<wx;x++){
                cin>>room[x][y];
                if(room[x][y]=='@'){//记录起点位置
                    dx=x;
                    dy=y;
                }
            }
        }
        num=0;
        bfs(dx,dy);
        cout<<num<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值