hdu 3152Obstacle Course bfs+优先队列

来源:互联网 发布:java公司官网模板源码 编辑:程序博客网 时间:2024/04/29 06:04


#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
using namespace std ;
const int maxn  = 130;
const int inf = 0x7fffffff;
int N;
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
int line[maxn][maxn];
int vis[maxn][maxn];
int ans = inf;
struct node
{
    int x,y;
    int sum ;
};
struct cmp{
    bool operator ()(struct node &a,struct node &b){
        return a.sum>b.sum;//最小值优先
    }
};
void bfs()
{
   priority_queue<struct node,vector<struct node>,cmp> que;
   struct node first = {1,1,line[1][1]};
   vis[1][1] = 1;
   que.push(first);
   while(que.size())
   {
       struct node now = que.top();
       que.pop();
       if(now.sum > ans)
       continue ;
       if(now.x == N &&now.y == N)
       ans = min(ans,now.sum);
       for(int i = 0;i < 4;i++)
       {
           int x1 = now.x + dx[i] ;
           int y1 = now.y + dy[i] ;
           if(!vis[x1][y1]&&(x1>=1)&&(x1<=N)&&(y1>=1)&&(y1<=N))
           {
               struct node next={x1,y1,line[x1][y1]+now.sum};
               vis[x1][y1] = 1;
               que.push(next);
           }
        }
   }
}
int main()
{
   // freopen("in.txt","r",stdin);
    int cas = 0;
    while(scanf("%d",&N)&&N)
    {
       for(int i = 1 ;i <= N ;i++)
          for(int j = 1;j <= N ;j++)
          scanf("%d",&line[i][j]);
        ans = inf ;
        memset(vis,0,sizeof(vis));
        bfs();
        printf("Problem %d: ",++cas);
        printf("%d\n",ans);
    }
    return 0;
}









































































































0 0
原创粉丝点击