2806 红与黑

2806 红与黑

 

 时间限制: 1 s
 空间限制: 64000 KB
 题目等级 : 白银 Silver
 
 
题目描述 Description

有一个矩形房间,覆盖正方形瓷砖。每块瓷砖涂成了红色或黑色。一名男子站在黑色的瓷砖上,由此出发,可以移到四个相邻瓷砖之一,但他不能移动到红砖上,只能移动到黑砖上。编写一个程序,计算他通过重复上述移动所能经过的黑砖数。

 

输入描述 Input Description

输入包含多个数据集。一个数据集开头行包含两个正整数W和H,W和H分别表示矩形房间的列数和行数,且都不超过20.
每个数据集有H行,其中每行包含W个字符。每个字符的含义如下所示:
'.'——黑砖
'#'——红砖
'@'——男子(每个数据集仅出现一次)
两个0表示输入结束。

输出描述 Output Description

对每个数据集,程序应该输出一行,包含男子从初始瓷砖出发可到达的瓷砖数。

样例输入 Sample Input

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

样例输出 Sample Output

45
59
6
13

数据范围及提示 Data Size & Hint

分类标签 Tags 

 大水题,字符串读错了,调了半天

dfs版

#include<cstdio>
#include<cstring>
using namespace std;
#define N 22
int s,h,w,vis[N][N];
char b[N][N],c[N];
void dfs(int x,int y){
    if(x<1||x>h||y<1||y>w||b[x][y]=='#') return ;
    if(vis[x][y]) return ;
    if(b[x][y]=='.'){
        s++;vis[x][y]=1;
    }
    dfs(x+1,y);
    dfs(x,y+1);
    dfs(x-1,y);
    dfs(x,y-1);
}
int main(){
    for(;scanf("%d%d",&w,&h)!=EOF&&w&&h;){
        s=1;
        memset(vis,0,sizeof vis);
        int x,y;
        for(int i=1;i<=h;i++){
            scanf("%s",c);
            for(int j=1;j<=w;j++){
                b[i][j]=c[j-1];
                if(b[i][j]=='@') x=i,y=j;    
            }
        }
        dfs(x,y);
        printf("%d\n",s);
    }
    return 0;
}

bfs

#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
#define N 301
int w,h,dx[]={1,0,0,-1},dy[]={0,1,-1,0};
struct node{
    int x,y;
}now,next;
queue<node>q;
char str[N];
int a[N][N],vis[N][N];
inline void bfs(){
    //while(!q.empty()) q.pop();
    int cnt=1;
    vis[now.x][now.y]=1;
    q.push(now);
    while(!q.empty()){
        now=q.front();
        q.pop();
        for(int j=0;j<4;j++){
            next.x=dx[j]+now.x;
            next.y=dy[j]+now.y;
            if(next.x<0||next.y<0||next.x>=h||next.y>=w);else          
            if(!vis[next.x][next.y]&&!a[next.x][next.y]){
                vis[next.x][next.y]=1;
                q.push(next);
                cnt++;
            }    
        }  
    }  
    printf("%d\n",cnt);
    for(int i=0;i<h;i++)
        for(int j=0;j<w;j++)
            vis[i][j]=0,a[i][j]=0;
}
int main(){
    while(scanf("%d%d",&w,&h)==2&&w&&h){
        for(int i=0;i<h;i++){
            scanf("%s",str);
            for(int j=0;j<w;j++){
                if(str[j]=='#')
                    a[i][j]=1;
                else if(str[j]=='@')
                    now.x=i,now.y=j;    
            }
        }
        bfs();    
    }
    return 0;
}

 

 

posted @ 2016-06-11 11:25  神犇(shenben)  阅读(214)  评论(0编辑  收藏  举报