DFS(深度优先搜索)

Red and Black


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.
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.
输入由多个数据集组成。一个数据集以一个包含两个正整数W和H的线开始;W和H分别是x-和y-方向上的块数。W和H不超过20。
数据集中还有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).
对于每个数据集,您的程序应该输出一条线,其中包含从初始瓦片(包括它自己)可以到达的瓦片数量。
修改翻译结果


**Sample Inpu**t
6 9
….#.
…..#
……
……
……
……
……
#
@…#
.#..#.


11 9
.#………
.#.#######.
.#.#…..#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#…….#.
.#########.


………..
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..


7 7
..#.#..
..#.#..

.

…@…

.

..#.#..
..#.#..
0 0


Sample Output
45
59
6
13


思路:简单的应用DFS就可以了,主要是要理解DFS中的递归部分


#include<stdio.h>
#include<cstdio>
#include<bits/stdc++.h>
const int  MAX=50;
int ans,w,k;
char a[MAX][MAX];
int vis[MAX][MAX];
int d[2][4]={{1,-1,0,0},{0,0,1,-1}};
void DFS(int x,int y)
{   
    vis[x][y]=1;
    ans++;
    for(int i=0;i<4;i++)
    {
        int dx = x + d[0][i];
        int dy = y + d[1][i];
        if(dx>=0&&dx<k&&dy>=0&&dy<w&&vis[dx][dy]!=1&&a[dx][dy]!='#')
            DFS(dx,dy);
    }
}
int main()
{
    int i,j;
    while(~scanf("%d%d",&w,&k)&&(w+k)!=0)  //k行w列 
    {   memset(vis,0,sizeof(vis));
        ans=0;
        for(i=0;i<k;i++)
        {
            scanf("%s",a[i]);
        }
        for(i=0;i<k;i++)
        {
            for(j=0;j<w;j++)
                if(a[i][j]=='@')
                {   DFS(i,j);
                    break;
                }   
        }   
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shf1730797676/article/details/81326447