hdu 1312 Red and Black(BFS)

简介: hdu 1312 Red and Black(BFS)

题目描述


有一个长方形的房间,铺着方形瓷砖。每块瓷砖都涂上红色或黑色。一个男人站在黑色的瓷砖上。从瓦片,他可以移动到四个相邻的瓷砖之一。但他不能在红瓦上移动,他只能在黑瓦上移动。


编写一个程序,通过重复上述步骤来计算他可以达到的黑色瓷砖的数量。


输入


输入由多个数据集组成。数据集以包含两个正整数W和H的行开始; W和H分别是x方向和y方向上的瓦片数量。W和H不超过20.


数据集中有更多的行,每个行包含W个字符。每个字符表示一个瓦片的颜色如下。


’ . ’ - 黑色瓦片


‘#’ - 红色瓦片


‘@’ - 黑色瓦片上的男士(在数据集中恰好出现一次)


输入的末尾由包含两个零的行表示。


输出


对于每个数据集,程序应该输出一行,其中包含他可以从初始图块(包括自身)到达的图块数量。


样例输入


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


样例输出


45
59
6
13


代码


#include<iostream>  
#include<cstring>  
#include<cstdio>  
using namespace std;
// n行m列   vis迷宫图   ans黑瓦个数(每执行一次dfs函数就找到一个,并且第一片肯定是黑瓦)
int n, m, vis[30][30], ans;
int fx[4] = { 0,0,1,-1 }, fy[4] = { 1,-1,0,0 };//用来记录移动的xy方位  
char tile[30][30];//记录迷宫  
void dfs(int x, int y) 
{
  ans++;          //计算步数  
  vis[x][y] = 1;      //将此位置记录 已走过 
  for (int i = 0; i < 4; i++)
  {  
    //向四个方位分别搜索 
    int nx = x + fx[i];
    int ny = y + fy[i];
    if (nx >= 0 && nx < n&&ny >= 0 && ny < m
      && !vis[nx][ny] && tile[nx][ny] == '.')//判断是否越界是否走过是否可走  
      dfs(nx, ny);
  }
}
int main() 
{
  while (cin >> m >> n, m != 0, n != 0) 
  {
    ans = 0;
    memset(vis, 0, sizeof(vis));
    for (int i = 0; i < n; i++)
      cin >> tile[i];
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
        // 找人的位置
        if (tile[i][j] == '@' && !vis[i][j])
        {
          dfs(i, j);
          break;
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
相关文章
|
9月前
|
Java
hdu-1312-Red and Black
hdu-1312-Red and Black
42 0
HDU - 1312 Red and Black(DFS)
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
96 0
|
C++
【PAT甲级 - C++题解】1135 Is It A Red-Black Tree
【PAT甲级 - C++题解】1135 Is It A Red-Black Tree
116 0
|
C++
【PAT甲级 - C++题解】1033 To Fill or Not to Fill
【PAT甲级 - C++题解】1033 To Fill or Not to Fill
87 0
hdu 1312 Red and Black
一个人从@点出发,求他所能到达的'.'的数目,'#'不可走,@本身算1个点。 思路:搜索入门题。
165 0
|
机器学习/深度学习
HDOJ/HDU 1556 Color the ball(树状数组)
HDOJ/HDU 1556 Color the ball(树状数组)
110 0
HDOJ 1312 (POJ 1979) Red and Black
HDOJ 1312 (POJ 1979) Red and Black
121 0
【1069】The Black Hole of Numbers (20 分)
【1069】The Black Hole of Numbers (20 分) 【1069】The Black Hole of Numbers (20 分)
111 0