HDU1312 BFS-Numerically Speaking

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

题意:


长方形地面铺有红砖和黑砖,人站在其中一块黑砖上,只能走黑砖不能走红砖,并且只能走前后左右的四块砖,不能往斜向走,问这个人能到达的黑砖有多少块;


题解:


简单的深度优先搜索问题,从起点开始向四个方向搜索,用一个队列保存是黑砖的点的坐标,接着往下面搜索,一直到队列为空,此时就可以遍历所有能够到达的店。


#include 
#include 
#include 
#define MAXN 20+5
using namespace std;
char tile[MAXN][MAXN];
bool vis[MAXN][MAXN];
int w,h;
int sum;
//(dx,dy)表示四个方向
const int dx[] = {0,1,0,-1};
const int dy[] = {-1,0,1,0};
queue<int> q;

void bfs(int i, int j)
{
    while(!q.empty()) q.pop();
    q.push(i*h+j);//哈希法表示点的坐标
    while(!q.empty())
    {
        int u = q.front();
        q.pop();
        //cout << u << endl;
        int cx, cy;
        cx = u/h;
        cy = u%h;
        //cout << cx << " " << cy << endl;
        for(int k = 0; k < 4; k++)
        {
            int nx,ny;
            nx = cx + dx[k];
            ny = cy + dy[k];
            if(nx >= 0 && nx < w && ny >= 0&& ny < h && tile[nx][ny] == '.' && vis[nx][ny] == false)
            {
                vis[nx][ny] = true;
                q.push(nx*h+ny);
                sum++;
            }
        }
    }
}

int main()
{
    while(cin >> h >> w && h != 0 && w != 0)
    {
        int x0=0, y0=0;
        memset(vis, 0, sizeof(vis));
        sum = 1;
        for(int i = 0; i < w; i++)
            for(int j = 0; j < h; j++)
            {
                cin >> tile[i][j];
                if(tile[i][j] == '@')
                {
                    x0 = i;
                    y0 = j;
                }
            }
        bfs(x0,y0);
        //cout << x0 << " " << y0 << endl;
        cout << sum << endl;
    }
    return 0;
}

你可能感兴趣的:(BFS)