2806 红与黑

Posted 神犇(shenben)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#[email protected]#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
[email protected]
###.###
..#.#..
..#.#..
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;
}o,t;
queue<node>q;
char str[N];
int a[N][N],vis[N][N];
inline void bfs(){
    int cnt=0;
    q.push(o);
    while(!q.empty()){
        o=q.front();
        for(int j=0;j<4;j++){
            t.x=dx[j]+o.x;
            t.y=dy[j]+o.y;
            if(t.x<0||t.y<0||t.x>=h||t.y>=w);else          
            if(!vis[t.x][t.y]&&!a[t.x][t.y]){
                vis[t.x][t.y]=1;
                q.push(t);
                cnt++;
            }  
            
        }
        q.pop();
    }  
    if(cnt==0) 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;i++){
                if(str[j]==#)
                    a[i][j]=1;
                else if(str[j]==@)
                    o.x=i,o.y=j;    
            }
        }
        bfs();    
    }
    return 0;
}

 

以上是关于2806 红与黑的主要内容,如果未能解决你的问题,请参考以下文章

codevs 2806 红与黑

codevs2806 红与黑

codevs 2806 红与黑

广度优先搜索 codevs 2806 红与黑

codevs——T2806 红与黑

红与黑