杭电1312题搜索算法

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1312

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
/* .可以走,#是墙不能走,@表示起点,搜索算法 */
struct node   //点的结构体
{
    int x;   //x轴的坐标
    int y;  //y轴的坐标
};
queue<node>q;   //广搜需要用到的队列
char maze[105][105];  //存入数据的数组
bool vis[105][105];//记录轨迹
bool xin[105][105];//记录是否收录此结点
int n,m,total;
int dx[4]={1,-1,0,0};  //四个方向
int dy[4]={0,0,1,-1};  //四个方向
void bfs(node t)  //广度优先搜索
{
   node g,h;
   q.push(t);
   while(!q.empty())   //当队列为空时,即无路可走
   {
       g=q.front();
       vis[g.x][g.y]=true;   //标记当前节点已经走过
       if(!xin[g.x][g.y])
       {
          total++;
          xin[g.x][g.y]=true;
       }
       for(int i=0;i<4;i++)
       {
           h.x=g.x+dx[i];   h.y=g.y+dy[i];
           if(h.x>=0&&h.x<m&&h.y>=0&&h.y<n&&!vis[h.x][h.y]&&maze[h.x][h.y]=='.')
            q.push(h);
       }
       q.pop();
   }
}
void dfs(node t)  //深度优先搜索
{
    node h;
    if(!xin[t.x][t.y])
    {
        total++;
        xin[t.x][t.y]=true;
    }
    for(int i=0;i<4;i++)
    {
       h.x=t.x+dx[i];  h.y=t.y+dy[i];
       if(h.x>=0&&h.x<m&&h.y>=0&&h.y<n&&!vis[h.x][h.y]&&maze[h.x][h.y]=='.')
       {
           vis[h.x][h.y]=true;
           dfs(h);//不需要回溯
       }
    }
}
int main()
{
    int x1,y1;
    node h;
    while(cin>>n>>m)//m为行,n为列
    {
        if(n==0&&m==0)  break;
        total=0;
        memset(vis,false,sizeof(vis));
        memset(xin,false,sizeof(xin));
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
             {
                cin>>maze[i][j];
                if(maze[i][j]=='@')
                {
                    h.x=i;  h.y=j;  //记录起点
                }
             }
        dfs(h);
        while(!q.empty())  q.pop();  //用完广度优先搜索,一定要清空队列
        cout<<total<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39905917/article/details/84502034