hdu1312 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. 
InputThe 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) 
OutputFor 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

解題思路:這是一道bfs的題目,在每次push的時候,就將答案加一

代碼:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int hang,lie;
char a[25][25];
int vis[25][25];
int dis[][2] = {{1,0},{0,1},{-1,0},{0,-1}};
struct node
{
    int x;
    int y;
};

int ok(int aa,int b)
{
    if(aa>=0&&aa<hang&&b>=0&&b<lie&&a[aa][b]=='.')
        return true;
    else return false;
}

int bfs(node now)
{
    int ans = 0;
    node help ;
    node help2 ;
    queue<node> q;
    q.push(now);
    vis[now.x][now.y] = 1;
    while(!q.empty())
    {
        help = q.front();
        q.pop();
        for(int i = 0;i<4;i++)
        {
            help2.x = help.x+dis[i][0];
            help2.y = help.y+dis[i][1];
            if(!vis[help2.x][help2.y]&&ok(help2.x,help2.y))
            {
                q.push(help2);
                vis[help2.x][help2.y] = 1;
                ans++;
            }
        }
    }
    return ans;
}

int main()
{
    while(cin>>lie>>hang)
    {
        if(lie==0||hang==0)
            break;
        memset(vis,0,sizeof(vis));
        node pos ;
        for(int i = 0;i<hang;i++)
            for(int j = 0;j<lie;j++)
        {
            cin>>a[i][j];
            if(a[i][j]=='@')
            {
                pos.x = i;
                pos.y = j;
            }
        }
        int re = bfs(pos);
        cout<<re+1<<endl;
    }
}


發佈了79 篇原創文章 · 獲贊 1 · 訪問量 8912
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章