【BFS】HDU3152Obstacle Course

来源:互联网 发布:sqlserver中union 编辑:程序博客网 时间:2024/05/24 06:38

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

Problem Description


You are working on the team assisting with programming for the Mars rover. To conserve energy, the rover needs to find optimal paths across the rugged terrain to get from its starting location to its final location. The following is the first approximation for the problem.


N * N square matrices contain the expenses for traversing each individual cell. For each of them, your task is to find the minimum-cost traversal from the top left cell [0][0] to the bottom right cell [N-1][N-1]. Legal moves are up, down, left, and right; that is, either the row index changes by one or the column index changes by one, but not both.
 

Input
Each problem is specified by a single integer between 2 and 125 giving the number of rows and columns in the N * N square matrix. The file is terminated by the case N = 0.

Following the specification of N you will find N lines, each containing N numbers. These numbers will be given as single digits, zero through nine, separated by single blanks.
 

Output
Each problem set will be numbered (beginning at one) and will generate a single line giving the problem set and the expense of the minimum-cost path from the top left to the bottom right corner, exactly as shown in the sample output (with only a single space after "Problem" and after the colon).
 

Sample Input
35 5 43 9 13 2 753 7 2 0 12 8 0 9 11 2 1 8 19 8 9 2 03 6 5 1 579 0 5 1 1 5 34 1 2 1 6 5 30 7 6 1 6 8 51 1 7 8 3 2 39 4 0 7 6 4 15 8 3 2 4 8 37 4 8 4 8 3 40
 

Sample Output
Problem 1: 20Problem 2: 19Problem 3: 36

题目意思:

给你一个N*N的矩阵,找(0,0)到(n-1,n-1)的最短路

代码:

#include<iostream>#include<queue>#include<cstring>#include<string>using namespace std;int a[150][150];int vis[150][150];int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};int ans;int n;struct node{    int x,y;        //  位置    int dis;        //  路径    friend bool operator <(node a,node b)    {        return a.dis>b.dis;    }};bool isOk(int x,int y){    return x>=0&&y>=0&&x<n&&y<n;}void bfs(){    priority_queue<node>q;    node st;    st.x=0;    st.y=0;    st.dis=a[0][0];    vis[0][0]=1;    q.push(st);    while(!q.empty()){        st=q.top();        q.pop();        if(st.x==n-1&&st.y==n-1){            ans=st.dis;            return;        }        for(int i=0;i<4;i++){            node nt=st;            nt.x+=dir[i][0];            nt.y+=dir[i][1];            if(!vis[nt.x][nt.y]&&isOk(nt.x,nt.y)){                vis[nt.x][nt.y]=1;                nt.dis+=a[nt.x][nt.y];                q.push(nt);            }        }    }}int main(){    int Case=1;    while(cin>>n&&n){        ans=0;        memset(vis,0,sizeof(vis));        for(int i=0;i<n;i++){            for(int j=0;j<n;j++){                cin>>a[i][j];            }        }        bfs();        cout<<"Problem "<<Case++<<": "<<ans<<endl;    }    return 0;}


0 0
原创粉丝点击