解题思路
这是一个最短路径问题,需要找出从起点 到任意陷阱位置的最短曼哈顿距离。
关键点:
- 从 到任意点的最短路径就是曼哈顿距离
- 需要计算到每个陷阱的距离并找出最小值
- 曼哈顿距离 =
算法步骤:
- 读取所有陷阱的坐标
- 计算从起点到每个陷阱的曼哈顿距离
- 返回最小距离
代码
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minTimeToTrap(int n, vector<int>& x, vector<int>& y) {
int minTime = INT_MAX;
// 计算到每个陷阱的最短距离
for (int i = 0; i < n; i++) {
// 曼哈顿距离 = |x1-x2| + |y1-y2|
int distance = abs(x[i] - 1) + abs(y[i] - 1);
minTime = min(minTime, distance);
}
return minTime;
}
};
int main() {
int n;
cin >> n;
vector<int> x(n), y(n);
// 读取横坐标
for (int i = 0; i < n; i++) {
cin >> x[i];
}
// 读取纵坐标
for (int i = 0; i < n; i++) {
cin >> y[i];
}
Solution solution;
cout << solution.minTimeToTrap(n, x, y) << endl;
return 0;
}
import java.util.*;
public class Main {
static class Solution {
public int minTimeToTrap(int n, int[] x, int[] y) {
int minTime = Integer.MAX_VALUE;
// 计算到每个陷阱的最短距离
for (int i = 0; i < n; i++) {
// 曼哈顿距离 = |x1-x2| + |y1-y2|
int distance = Math.abs(x[i] - 1) + Math.abs(y[i] - 1);
minTime = Math.min(minTime, distance);
}
return minTime;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] x = new int[n];
int[] y = new int[n];
// 读取横坐标
for (int i = 0; i < n; i++) {
x[i] = sc.nextInt();
}
// 读取纵坐标
for (int i = 0; i < n; i++) {
y[i] = sc.nextInt();
}
Solution solution = new Solution();
System.out.println(solution.minTimeToTrap(n, x, y));
sc.close();
}
}
class Solution:
def min_time_to_trap(self, n: int, x: list, y: list) -> int:
min_time = float('inf')
# 计算到每个陷阱的最短距离
for i in range(n):
# 曼哈顿距离 = |x1-x2| + |y1-y2|
distance = abs(x[i] - 1) + abs(y[i] - 1)
min_time = min(min_time, distance)
return min_time
# 读取输入
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
solution = Solution()
print(solution.min_time_to_trap(n, x, y))
算法及复杂度
- 算法:曼哈顿距离计算
- 时间复杂度:,其中 是陷阱数量
- 空间复杂度: