zoukankan      html  css  js  c++  java
  • hdu-1728(bfs+优化)

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

    注意:1、先输入起点(y1,x1)和终点(y2,x2);

    2、如果一个一个遍历会超时。

    思路:每次将整一行或列的点全部遍历,然后再寻找是否找过某个点。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<queue>
    using namespace std;
    int n,m,x1,y1,x2,y2,k;
    char a[120][120];
    struct Node{
        int x,y,step;
    };
    int vis[120][120],zz[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
    bool pd(int x,int y)
    {
        if(x<0||x>=n||y<0||y>=m||a[x][y]=='*') return false;
        return true;
    }
    void bfs()
    {
        if(x1==x2&&y1==y2)
        {
            cout<<"yes"<<endl;
            return ;
        }
        queue <Node> q;
        memset(vis,0,sizeof(vis));
        Node tmp,tp;
        tmp.x=x1-1;tmp.y=y1-1;tmp.step=-1;
        vis[x1-1][y1-1]=1;
        q.push(tmp);
        while(!q.empty())
        {
            tmp=q.front();
            q.pop();
            for(int i=0;i<4;i++)
            {
                tp.x=tmp.x+zz[i][0];
                tp.y=tmp.y+zz[i][1];
                while(pd(tp.x,tp.y))
                {
                    if(vis[tp.x][tp.y]==0)
                    {
                        tp.step=tmp.step+1;
                        vis[tp.x][tp.y]=1;
                        if(tp.x==x2-1&&tp.y==y2-1&&tp.step<=k)
                        {
                            cout<<"yes"<<endl;
                            return ;
                        }
                        q.push(tp);
                    }
                    tp.x+=zz[i][0];
                    tp.y+=zz[i][1];
                }
            }
        }
        cout<<"no"<<endl;
        return ;
    }
    
    int main(void)
    {
        int i,j,T;
        cin>>T;
        while(T--)
        {
            cin>>n>>m;
            for(i=0;i<n;i++) scanf("%s",a[i]);
            cin>>k>>y1>>x1>>y2>>x2;
            bfs();
        }
        return 0;
    } 
    View Code

    参考文章:https://blog.csdn.net/flynn_curry/article/details/52901207

  • 相关阅读:
    node V8 的垃圾回收机制
    Array、ArrayList 区别
    二分查找算法,java实现
    Arrays、ArrayUtils 区别
    Collection与Collections,Array与Arrays的区别
    (String)、toString、String.valueOf的区别
    Vuejs项目的Webpack2构建优化
    webpack 的插件 DllPlugin 和 DllReferencePlugin
    webpack externals
    手工配置rsyslog配置文件详解
  • 原文地址:https://www.cnblogs.com/2018zxy/p/9818634.html
Copyright © 2011-2022 走看看