Red and Black

Problem Description
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can’t move on red tiles, he can move only on black tiles.(问题描述 ;有一个长方形的房间,上面铺着方形瓷砖。每块瓷砖都是红色或黑色的。一个男人站在一块黑色的瓷砖上。从一个瓷砖,他可以移动到四个相邻的瓷砖之一。但是他不能在红瓦上移动,他只能在黑瓦上移动。。 )

Write a program to count the number of black tiles which he can reach by repeating the moves described above.(写一个程序,通过重复上面描述的动作来计算他可以到达的黑瓷砖的数量。)

Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.(输入 ;输入由多个数据集组成。一个数据集以包含两个正整数W和H的一行开始;w和H分别是x和y方向的瓷砖数量。w和H不超过20。 )

There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.(数据集中多了H行,每一行都包含W个字符。每个字符代表一个图块的颜色,如下所示。 )

‘.’ - a black tile(’.’-一块黑色瓷砖 。)
‘#’ - a red tile (#’ -一块红色的瓷砖 。)
‘@’ - a man on a black tile(appears exactly once in a data set (@’ -一个在黑瓷砖上的人(在数据集中出现一次) 。)

Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).(输出 ;对于每个数据集,您的程序应该输出一行,其中包含他可以从初始图块(包括其本身)到达的图块数量。)

#include<stdio.h>
int dir[4][2]= {{1,0},{0,-1},{0,1},{-1,0}};|| 四表示为上下左右,二表示为黑色或者红色。
char a[22][22];  || 定义个数组为这个房间的砖块数(二维)。
int num,m,n; || num代表能走的黑砖个数,m,n分别表示行和列的砖块数。
void DFS(int x,int y) ||深度优先遍历这个数组,x,y为一块砖的位置。
{
    num++; 黑砖的个数随着遍历 加一。
    a[x][y]='#';|| 防止重复记录
    for(int i=0;i<4; i++) || 从现在这个人站着的砖块开始探索,小于四是指在上下左右这个范围内,每次探索加一。
    {
        int p,q;
        p=x+dir[i][0];
        q=y+dir[i][1]; || 定义个p,q,表示下一个位置的横纵坐标。
        if(p>=0&&q>=0&&p<m&&q<n&&a[p][q]=='.') || 若下个坐标是黑砖。
        {
            DFS(p,q);  || 继续从此位置探索访问下去。
        }
    }
}
int main()
{
    int i,j; || 定义i,j为横坐标和总左边的砖块数的编号。
    while(scanf("%d%d",&n,&m)&&n>0&&m>0)  || 输入m,n 且循环。
    {
        num=0; || 每一次都初始化0
        getchar(); || 
        for(i=0;i<m; i++) || 横坐标从i=0开始循环。
            scanf("%s",a[i]); || 一行一行的输入。
        for(i=0;i<m; i++) 
         for(j=0; j<n; j++)  || i,j从0开始循环探索,意思是每个砖块都要探索。
          if(a[i][j]=='@')  || 记录i,j。
                {
                   a[i][j]='#'; 
                    DFS(i,j); || i,j为红砖,继续遍历下去。
                    break; || 到最后所有的砖块都遍历一遍则结束。
                }
        printf("%d\n",num); || 输出能走的黑砖数量。
    }
    return 0;
}

getchar的用法详解。 深度优先遍历

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值