我试图开发一个代码来解决C语言中的旅行推销员问题,但是我有一些限制:我只能使用“for”、“while”、“do”、数组、矩阵和类似的简单东西,所以,没有函数或递归(不幸的是)。
到目前为止我得到的是:
用户将键入城市坐标x和y,如下所示:
8.15 1.58
9.06 9.71
1.27 9.57
9.13 4.85
存储坐标的代码。
float city[4][2];
int i;
for (i=0; i<4; i++)
scanf("%f %f", &cidade[i][0], &cidade[i][1]);
有4个城市,所以“我”从0变为3x和y存储在矩阵的第二维度上,[0]和[1]。
现在的问题是,我必须生成矩阵的第一维的所有可能的置换只有4个城市似乎很容易,因为所有可能的路线都是(每次都必须从城市A开始):
A B C D
A B D C
A C B D
A C D B
A D C B
A D B C
但我得把它扩展到10个城市。人们告诉我它将使用9个嵌套的foor循环,但我无法开发它=(
有人能给我个主意吗?
最佳答案
扩展到10(并查找城市名称)作为读者的练习。很可怕,但这就是你教授的局限性
#include <stdio.h>
int main(void) {
for (int one = 0; one < 4; one++) {
for (int two = 0; two < 4; two++) {
if (two != one) {
for (int three = 0; three < 4; three++) {
if (one != three && two != three) {
for (int four = 0; four < 4; four++)
if (one != four && two != four && three != four) {
printf("%d %d %d %d\n", one, two, three, four);
}
}
}
}
}
}
return 0;
}