2014
03-06

# Obstacle Course

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.

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.

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.

3
5 5 4
3 9 1
3 2 7
5
3 7 2 0 1
2 8 0 9 1
1 2 1 8 1
9 8 9 2 0
3 6 5 1 5
7
9 0 5 1 1 5 3
4 1 2 1 6 5 3
0 7 6 1 6 8 5
1 1 7 8 3 2 3
9 4 0 7 6 4 1
5 8 3 2 4 8 3
7 4 8 4 8 3 4
0

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

/**
* ID: ping128
* LANG: C++
*/

#include <stdio.h>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <list>
#include <math.h>
#include <algorithm>
#include <map>
#include <string.h>

using namespace std;

typedef long long LL;
typedef pair<int, int>PII;
typedef pair<PII, int>PII2;

int n;
int in[150][150];
int dp[150][150];

int cx[] = {0, 0, 1, -1}, cy[] = {1, -1, 0, 0};

class Solve
{
public:
void main2()
{
for(int i = 0; i < n; i++ )
for(int j = 0; j < n; j++ )
cin >> in[i][j];
for(int i = 0; i < n; i++ )
for(int j = 0; j < n; j++ )
dp[i][j] = 1000000000;
dp[0][0] = in[0][0];
queue<PII>Q;
Q.push(PII(0, 0));
while(!Q.empty())
{
int ii = Q.front().first;
int jj = Q.front().second;
Q.pop();
for(int i = 0; i < 4; i++ )
{
int iii = ii + cx[i];
int jjj = jj + cy[i];
if(iii >= 0 && iii < n && jjj >= 0 && jjj < n && dp[iii][jjj] > dp[ii][jj] + in[iii][jjj])
{
dp[iii][jjj] = dp[ii][jj] + in[iii][jjj];
Q.push(PII(iii,jjj));
}
}
}
cout << dp[n - 1][n - 1] << endl;
}
};

int main()
{
// freopen("c.in", "r", stdin);
// freopen(".out", "w", stdout);
int t= 0 ;
while(1)
{
t++;
cin >> n;
if(n == 0) break;
Solve ___test;
printf("Problem %d: ", t);
___test.main2();
}
//while(1);
return 0;
}

1. [email protected]