HDU T3152 Obstacle Course

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


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).
 

BFS + 优先队列优化

简单题

 1 #include <cstdio>
 2 #include <queue>
 3 using namespace std;
 4 
 5 struct cord {
 6     int x, y;
 7     int sum;
 8     friend bool operator<(cord x, cord y) {
 9         return x.sum > y.sum;
10     }
11 };
12 
13 int main() {
14     int kase = 1;
15     int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
16     int N;
17 
18     while(~scanf("%d", &N) && N) {
19         int mapp[N][N];
20         bool visited[N][N];
21 
22         for(int i = 0; i < N; i++) {
23             for(int j = 0; j < N; j++) {
24                 scanf("%d", &mapp[i][j]);
25                 visited[i][j] = false;
26             }
27         }
28 
29         cord x, y;
30         priority_queue<cord> pq;
31         x.x = 0;x.y = 0;
32         x.sum = mapp[0][0];
33         pq.push(x);
34 
35         while(!pq.empty()) {
36             x = pq.top();pq.pop();
37             if(x.x == N-1 && x.y == N-1) {
38                 printf("Problem %d: %d\n", kase++, x.sum);
39                 break;
40             }
41 
42             for(int i = 0; i < 4; i++) {
43                 y.x = x.x + dir[i][0];
44                 y.y = x.y + dir[i][1];
45                 if(y.x < 0 || y.x >= N || y.y < 0 || y.y >= N || visited[y.x][y.y] == true) {
46                     continue;
47                 }
48                 y.sum = x.sum + mapp[y.x][y.y];
49                 pq.push(y);
50                 visited[y.x][y.y] = true;
51             }
52         }
53     }
54     return 0;
55 }

 

posted @ 2017-12-05 17:27  stvn  阅读(167)  评论(0编辑  收藏  举报