poj 1979 bfs

来源:互联网 发布:八陆融通网络借贷 编辑:程序博客网 时间:2024/06/05 11:12

题目大意:求从起点开始能够经过的黑格子的数目,红格子不能走,走的过程中,格子可以重复经过

解题思路:水题~~bfs,只要求出bfs能扩展的节点数就是格子数目

#include <iostream>#include <cstdio>#include <queue>#include <cstring>using namespace std;const int maxn = 21;struct node{    int x, y;};char rectangular[maxn][maxn];int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};int n, m, ans, sx, sy;void bfs();int main(){        while(true)    {        scanf("%d %d", &n, &m);        if(m == 0 && n == 0)            break;        ans = 0;        for(int i = 0; i < m; i++)        {            char *p;            scanf("%s", rectangular[i]);            if((p = strchr(rectangular[i], '@')) != NULL)                sx = i, sy = p - rectangular[i];        }        bfs();        printf("%d\n", ans);    }        return 0;}void bfs(){    queue<node> que;    node s;    s.x = sx;    s.y = sy;    que.push(s);    rectangular[sx][sy] = '#';    while(!que.empty())    {        node tmp = que.front();        que.pop();        ans++;        for(int i = 0; i < 4; i++)        {            int dx = tmp.x + dir[i][0];            int dy = tmp.y + dir[i][1];            if(dx >= 0 && dx < m && dy >= 0 && dy < n && rectangular[dx][dy] != '#')            {                rectangular[dx][dy] = '#';                node in;                in.x = dx; in.y = dy;                que.push(in);            }        }    }}