所以我一直在研究這個程序,它的目標是使用遞歸和鄰接矩陣來查找一個人可以通過一個地鐵系統而不需要經過多少條可能的路線跟蹤不止一次。對我來說,這是自我解釋,但現在我迷失在程序2上,它是從C++程序1中做同樣的問題,並使用三個類和遞歸。這些課程假定爲SubwaySystem,Station和Track。我真的不知道如何去從簡單的鄰接矩陣轉換到三個類?這似乎適得其反,因爲它似乎更復雜。我一直在研究它,並且似乎無法利用所有三個類。如何將C程序轉換爲類
我嘗試過的方法是:我的方法是我創建了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;
}
}
}
}
你想使用一個圖形,http://en.wikipedia.org/wiki/Graph_(data_structure),一個節點和邊,而不是一個鄰接矩陣。站是你的節點,軌道是你的邊緣,SubwaySystem是你的整個圖。一旦完成,您可能會發現節點/邊緣實施比鄰接矩陣更清晰。 –
有許多可行的解決方案。爲什麼不選擇一個? – aec