欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[POJ - 1979] Red and Black(DFS)

程序员文章站 2022-05-21 16:24:50
...

题目传送门:点传送
题目来源:Japan 2004 Domestic
Time Limit: 1000MS
Memory Limit: 30000K

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.
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.

‘.’ - a black tile
‘#’ - a red tile (不能走)
‘@’ - a man on a black tile(appears exactly once in a data set)
(起点)
The end of the input is indicated by a line consisting of two zeros.

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 Input

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

Sample Output

45
59
6
13

解析:
题意:从’@‘开始走能到达多少个’.’,注意’#‘是障碍,被它围起来的’.'是走不了的。
(走:上下左右)

代码

#include <stdio.h>
char a[20][20];
int W,H,cnt=0;//H为行 W为列 cnt为可到达点('.')的数量
int main(void)
{
    int dfs(int x,int y);
    int i,j,m,n;
    while(~scanf("%d%d",&W,&H))
    {
        if(W==0||H==0) continue;//特殊情况
        cnt=0;//初始化操作
        getchar();
        for(i=0;i<H;i++)
        {
            for(j=0;j<W;j++)
            {
                scanf("%c",&a[i][j]);
                if(a[i][j]=='@')
                    m=i,n=j;//记录起点
            }
            getchar();//清除换行
        }
        dfs(m,n);//从起点开始走
        printf("%d\n",cnt);
    }
}

int dfs(int x,int y)
{
    if(x>=0&&x<H&&y>=0&&y<W&&(a[x][y]=='.'||a[x][y]=='@'))
    {   
        a[x][y]='#';//走过的不再走
        cnt++;
        dfs(x+1,y);
        dfs(x-1,y);
        dfs(x,y+1);
        dfs(x,y-1);
    }
    return 0;
}

碎碎念
[POJ - 2386] Lake Counting (简单的DFS)
两题的dfs都简单应用于图的搜索,而且做法比较相似,对走过的点进行覆盖
(有的题目需要新建一个标记数组来记录是不是走过)

DFS的话,理解思想和模板代码后的话会相对轻松