题目描述:
宝宝和妈妈参加亲子游戏,在一个二维矩阵(N*N)的格子地图上,宝宝和妈妈抽签决定各自的位置,地图上每个格子有不同的糖果数量,部分格子有障碍物。
游戏规则是妈妈必须在最短的时间(每个单位时间只能走一步)到达宝宝的位置,路上的所有糖果都可以拿走,不能走障碍物的格子,只能上下左右走。
请问妈妈在最短到达宝宝位置的时间内最多拿到多少糖果(优先考虑最短时间到达的情况下尽可能多拿糖果)。
输入描述:
第一行输入为 N,N 表示二维矩阵的大小;
之后 N 行,每行有 N 个值,表格矩阵每个位置的值,其中:
-3:妈妈
-2:宝宝
-1:障碍
≥0:糖果数(0表示没有糖果,但是可以走)
输出描述 :
输出妈妈在最短到达宝宝位置的时间内最多拿到多少糖果,行末无多余空格
备注:地图最大 50*50
示例1:
输入
4
3 2 1 -3
1 -1 1 1
1 1 -1 2
-2 1 2 3
输出
9
示例2:
输入
4
3 2 1 -3
-1 -1 1 1
1 1 -1 2
-2 1 -1 3
输出
-1
C++源码:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAX_N = 50;
int dx[] = { 0, 1, 0, -1 };
int dy[] = { 1, 0, -1, 0 };
int n;
int grid[MAX_N][MAX_N];
int baby_x, baby_y, mom_x, mom_y;
struct State {
int x, y, steps, candies;
State(int x_, int y_, int steps_, int candies_) : x(x_), y(y_), steps(steps_), candies(candies_) {}
bool operator<(const State& other) const {
return steps > other.steps || (steps == other.steps && candies < other.candies);
}
};
bool isValid(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < n && grid[x][y] != -1;
}
int dijkstra() {
priority_queue<State> pq;
vector<vector<int>> visited(n, vector<int>(n, 0));
pq.push(State(mom_x, mom_y, 0, 0));
while (!pq.empty()) {
State current = pq.top();
pq.pop();
if (visited[current.x][current.y]) continue;
visited[current.x][current.y] = 1;
if (current.x == baby_x && current.y == baby_y) {
return current.candies;
}
for (int i = 0; i < 4; ++i) {
int nx = current.x + dx[i];
int ny = current.y + dy[i];
if (isValid(nx, ny)) {
int nextSteps = current.steps + 1;
int nextCandies = current.candies + grid[nx][ny];
if (!visited[nx][ny]) {
pq.push(State(nx, ny, nextSteps, nextCandies));
}
}
}
}
return -1;
}
int main() {
cin >> n;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> grid[i][j];
if (grid[i][j] == -3) {
mom_x = i;
mom_y = j;
}
else if (grid[i][j] == -2) {
baby_x = i;
baby_y = j;
}
}
}
int result = dijkstra();
cout << result << endl;
system("pause");
return 0;
}