mic*_*wal 5 c c++ arrays recursion class
所以我一直在研究这个项目,其目标是使用递归和邻接矩阵来找出一个人可以通过地铁系统可以采取多少条路线,而不必多次通过轨道.这对我来说是不言自明的,但现在我迷失在程序2上,这是从C++中的程序1和使用三个类和递归来做同样的问题.这些课程被认为是SubwaySystem,Station和Track.我真的不知道如何从简单的邻接矩阵过渡到三个类?这似乎适得其反,因为它似乎更复杂.我已经研究了一段时间了,我似乎无法利用所有三个班级.
我尝试过的方法:我的方法是创建1个地铁系统,有12个站点,每个站点都有一个轨道阵列.例如,站A有一个可以到达的站B.在站A中有一个由12个轨道组成的阵列,但只有1个轨道被激活.但是我继续运行错误,因为我尝试初始化Track类中的数组,然后在SubwaySystem类中使用它们.然后尝试使用递归来获取所有可能的路由使得它变得更加困难.我真的不知道如何解决这个问题.
我的代码中的邻接矩阵几乎映射了从站到站的整个连接.该站是对应于每行/列的A-L.我不知道如何在不使用邻接矩阵的情况下用c ++ 表示.
我在C中的代码(程序1):
#include <stdio.h>
void routesFinder(int row, int col);
char station[13] = "ABCDEFGHIJKL";
char order[25] = "A";
int subway[12][12] = {{0,1,0,0,0,0,0,0,0,0,0,0},
{1,0,1,1,1,1,0,0,0,0,0,0},
{0,1,0,0,1,0,0,0,0,0,0,0},
{0,1,0,0,1,0,0,0,0,0,0,0},
{0,1,1,1,0,0,1,1,0,0,0,0},
{0,1,0,0,0,0,0,1,0,0,0,0},
{0,0,0,0,1,0,0,0,0,0,1,0},
{0,0,0,0,1,1,0,0,1,1,1,0},
{0,0,0,0,0,0,0,1,0,0,1,0},
{0,0,0,0,0,0,0,1,0,0,1,0},
{0,0,0,0,0,0,1,1,1,1,0,1},
{0,0,0,0,0,0,0,0,0,0,1,0}};
int paths = 0, i = 1;
int main(){
routesFinder(0, 0); //start with first station row, first column
printf("\n%d days before repeating a route.\n", paths);
return 0;
}
void routesFinder(int row, int col) {
while (col < 12) { //go through columns of a row
if (subway[row][col] == 0) { // if no station is found in row
if (row == 11) { // station found
paths++;
printf("Route %d: %s.\n", paths, order);
return;
}
col++;
if (row != 11 && col == 12) { //backtracking from deadend
return;
}
}
if (subway[row][col] == 1) {
order[i] = station[col]; //add station to route
i++; //increment, prepare for next route
subway[row][col] = 0; //no track forward
subway[col][row] = 0; // or backward
routesFinder(col, 0); //recursion, look for path in new row
order[i] = '\0'; //remove route
i--; //decrement, prepare for next route
subway[row][col] = 1; //restore path
subway[col][row] = 1; // restore path
col++; //returning from deadend, check for next open path
if (row != 11 && col == 12) { //return from deadend
return;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
一种可能的方法是让地铁系统控制所有车站。然后,车站将拥有知道起点(它们来自哪个车站)和目的地(它们可以去哪个车站)的轨道。
邻接矩阵将被分解,整个事物在地铁系统内部表示,每一行/列在车站中表示,每个 1/0 由轨道表示。不会有零的轨道。
采取哪些路径将在车站级别决定,哪些轨道正在使用/目的地已经到达。轨道可以具有一个属性,可以在有人骑行时跟踪它们。