【发布时间】:2021-11-26 20:45:41
【问题描述】:
最近在求职面试中被问到类似的问题,我很难想出一个更有效的解决方案。
问题的规则,假设旅行是通过 x 轴完成的,为简单起见,从左到右:
- 在每一步中,您必须向右移动一个索引。
- 您可以从任意行开始。
- 您只能使用一行一次,直到您切换到另一行(因此不能返回一行)。
- 您可以切换到任何尚未使用的行。
目标是,鉴于这些限制,找到从左到右穿过阵列的最便宜的方式。
例子:
Array: {
{920, 239, 191, 267, 166, 879, 791, 998, 447, 617, 31, 169},
{361, 516, 506, 279, 406, 231, 828, 410, 408, 199, 507, 671},
{143, 69, 675, 847, 871, 704, 471, 796, 1000, 711, 42, 380},
{559, 407, 555, 390, 672, 415, 902, 570, 803, 29, 394, 937},
{407, 336, 427, 801, 509, 803, 267, 617, 47, 710, 529, 423},
{377, 26, 561, 950, 134, 343, 542, 342, 549, 65, 39, 900}
};
Result: 2634
Path: 143, 69, 506, 279, 134, 343, 542, 342, 47, 29, 31
我的示例代码:
#include <iostream>
#include <algorithm>
#include <list>
#include <sstream>
#include <set>
namespace stack_overflow_example {
int const x_dim = 6;
int const y_dim = 12;
int expected = 2634;
int arr[x_dim][y_dim] =
{
{920, 239, 191, 267, 166, 879, 791, 998, 447, 617, 31, 169},
{361, 516, 506, 279, 406, 231, 828, 410, 408, 199, 507, 671},
{143, 69, 675, 847, 871, 704, 471, 796, 1000, 711, 42, 380},
{559, 407, 555, 390, 672, 415, 902, 570, 803, 29, 394, 937},
{407, 336, 427, 801, 509, 803, 267, 617, 47, 710, 529, 423},
{377, 26, 561, 950, 134, 343, 542, 342, 549, 65, 39, 900}
};
int minimumValue = INT32_MAX;
void recursive_function(int x, int y, int value, std::set<int> unusedX) {
int summed = value + arr[x][y];
if (summed > minimumValue) {
return;
}
if ((y + 1) < y_dim) {
recursive_function(x, y + 1, summed, unusedX);
unusedX.erase(x);
for (auto const &i: unusedX) {
recursive_function(i, y + 1, summed, unusedX);
}
} else {
minimumValue = minimumValue < summed ? minimumValue : summed;
}
}
void calculate() {
std::set<int> unusedX;
for (int i = 0; i < x_dim; i++) {
unusedX.emplace(i);
}
for (int i = 0; i < x_dim; i++) {
recursive_function(i, 0, 0, unusedX);
}
std::cout << "Expected was: " << expected << " received " << minimumValue;
}
}
int main() {
stack_overflow_example::calculate();
}
我提出的解决方案可以正常工作,但算法复杂性很差,大小为 [12][24] 的数组已经花费了不可接受的时间来传输。招聘人员暗示有一个更快的答案,但我无法想出一个解决方案,这就是我希望你帮助的地方。任何编程语言都可以,我只是在 cpp 中发布了问题,因为它是我用来解决算法问题的语言。 提前致谢!
【问题讨论】:
-
阅读A* search algorithm,它可能不是您想要的——但它是一个很好的起点。
-
这正是使用动态编程的“接缝雕刻”所做的。只需谷歌它,你就会找到经典的解决方案。
-
我不明白,从哪里到哪里的最短路径?
-
更新了示例,使其更易于理解
-
我会采用蛮力方法枚举所有可能的路径,我不明白你的解决方案,但它看起来非常优雅,除了草率的后缀增量。
标签: c++ arrays algorithm path-finding