HDU 1312-Red and Black (DFS)

Red and Black

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25613    Accepted Submission(s): 15453


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.

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)
 

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
 
这道题就是套DFS的模板,只要理解DFS就能写出来。需要注意DFS递归调用的条件,也就是DFS剪枝(DFS剪枝即对DFS进行适当优化,满足条件则退出递归,不需要遍历完所有情况。)

代码:

#include <iostream>
#include <cstring>
using namespace std;
int dir[2][4]={ {
  1,-1,0,0} , {
  0,0,1,-1} };//四个方向 
int mp[21][21];//用来标记已经走过的点 
int w,h,t;
char c[21][21];

void DFS(int x,int y)//DFS核心代码 
{
    mp[x][y]=1;
    for(int i=0;i<4;i++)
    {
        int dx=x+dir[0][i];
        int dy=y+dir[1][i];
        if(c[dx][dy]=='.' && !mp[dx][dy])
        {
            t++;
            DFS(dx,dy);//满足条件则递归再次执行DFS函数,直到所有点都走完 
        } 
    }
}

int main()
{
    int i,j;
    while(cin>>w>>h && w,h)
    {
        t=1;
        memset(c,0,sizeof(c));
        memset(mp,0,sizeof(mp));//数组清除(初始化为0) 
        for(i=0;i<h;i++)
        for(j=0;j<w;j++)
        {
            cin>>c[i][j];
        }
        for(i=0;i<h;i++)
        {
            for(j=0;j<w;j++)
            {
                if(c[i][j]=='@') 
                {
                    break;
                }
            }
            if(c[i][j]=='@') break;
        }
        DFS(i,j);
        cout<<t<<endl;
    }
    return 0;
}
全部评论

相关推荐

我即大橘:耐泡王
点赞 评论 收藏
分享
11-08 17:36
诺瓦科技_HR
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务