简单搜索1979@POJ

来源:互联网 发布:安知鸿鹄之志上一句 编辑:程序博客网 时间:2024/05/16 04:19
....#......#..............................#@...#.#..#.  计算起始点@能达到的'.'的个数
利用广度优先搜索 对4个方向用队列保存下一个合理的状态
#include <iostream>#include <stdio.h>#include <queue>#define max 21using namespace std;int matrix[max][max];struct position{    int x,y;};int move[4][2]= {{-1,0},{0,1},{1,0},{0,-1}};position p;queue <position> q;int main(){    int W,H;    char c;    while(scanf("%d %d",&W,&H)==2&&(W!=0||H!=0))    {        int step=1;        getchar();        for(int i=1; i<=H; i++)        {            for(int j=1; j<=W; j++)            {                scanf("%c",&c);                if(c=='.')matrix[i][j]=1;                else if(c=='#')matrix[i][j]=0;                else                {                    matrix[i][j]=0;                    p.x=i;                    p.y=j;                }            }            getchar();        }        q.push(p);        while(!q.empty())        {            position nowtemp=q.front();            q.pop();            for(int i=0; i<4; i++)            {                position temp;                int tempx=nowtemp.x+move[i][0];                int tempy=nowtemp.y+move[i][1];                if(tempx<=H&&tempx>0&&tempy<=W&&tempy>0&&matrix[tempx][tempy]==1)                {                    temp.x=tempx;                    temp.y=tempy;                    step++;                    matrix[tempx][tempy]=0;                    q.push(temp);                }            }        }        printf("%d\n",step);    }    return 0;}
原创粉丝点击