C++ 执行函数时出现问题(递归)

C++ 执行函数时出现问题(递归),c++,arrays,function,recursion,C++,Arrays,Function,Recursion,该计划的目标是列举一个人通过地铁系统从a站到L站的所有可能路径,而无需多次越过轨道。我知道有640条可能的路径,正如指导老师告诉我们的,我们用邻接矩阵编写了这个程序,作为C语言的早期作业。现在的目标是做同样的事情,即枚举所有可能的路线,并打印出每条路线,除了使用类(特别是3类:SubwaySystem、Station和Track),而这次不使用矩阵。这是地铁系统本身的示意图 我和助教讨论了这个项目以及如何实施。他给了我一些想法,比如使用数组来表示车站和轨道,我决定使用我在文章底部的整个代码中展

该计划的目标是列举一个人通过地铁系统从a站到L站的所有可能路径,而无需多次越过轨道。我知道有640条可能的路径,正如指导老师告诉我们的,我们用邻接矩阵编写了这个程序,作为C语言的早期作业。现在的目标是做同样的事情,即枚举所有可能的路线,并打印出每条路线,除了使用类(特别是3类:SubwaySystem、Station和Track),而这次不使用矩阵。这是地铁系统本身的示意图

我和助教讨论了这个项目以及如何实施。他给了我一些想法,比如使用数组来表示车站和轨道,我决定使用我在文章底部的整个代码中展示的方法

让我向您展示我的代码中我无法解决的问题区域(递归对我来说是新的)

void SubwaySystem::SearchRoute(int当前站点ID)
{
if(my_station[当前_station\u ID]。track_start\u ID==33)//查找到车站L的成功路线。
//该条件设置为检查33,因为轨道起始ID为33将对应于车站L。
{
count_routes++;//将1添加到变量“count_routes”

我想你的主要问题是:

my_track[Current_Station_ID].visited = 1; //mark this track as visited
my_track[Current_Station_ID].node_2 = 1; //mark its corresponding track as visited
cout << my_track[Current_Station_ID].node_1; //save this track
SearchRoute(Current_Station_ID++); <<<<<<<< PROBLEM 
i--; //Backtrack this track  <<<<<<< Also this will do nothing
my_track[Current_Station_ID].visited = 0; <<<<<<< Now Current_Station_ID is 1 more than you are expecting it to be.
my_track[Current_Station_ID].node_2 = 0;//mark its corresponding track as unvisited

这是一个有效的解决方案,它给出了605个解决方案,我认为这是正确的

// RandomTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


#include <iostream>
#include <string>
using namespace std;






class Track
{
public:
    //Default Constructor
    Track();

    //Overload Constructor
    Track(char, char, int station, int opposite);

    //Destructor
    ~Track();

    //Member variables
    char node_1;  // node_1 and node_2 represent stations (for example
    char node_2;  // node_1 would be station A and node_2 would be station B)
    bool visited;

    int connected_station;
    int opposite_track;
};

class Station
{
public:
    //Default Constructor
    Station();

    //Destructor
    ~Station();

    //Overload Constructor
    Station(char, int, int);

    //Member variables
    char station_name;
    int track_starting_ID;
    int track_size;
};

class SubwaySystem
{
public:
    //Default Constructor
    SubwaySystem();

    //Destructor
    ~SubwaySystem();

    //Recursive function
    void SearchRoute(int);

    //Other member functions
    friend ostream& operator<<(ostream& os, const Track& my_track);
    friend ostream& operator<<(ostream& os, const Station& my_station);


    //Member variables
    Track my_track[34];
    Station my_station[12];

    int count_routes;
    int Current_Station_ID;

    //String to save found route

    void SearchRoute(int Current_Station_ID, int from_track_id, Track **currentPath, int pathCount);
};





// **cpp**


//#include "subway.h"

using namespace std;

Track::Track()
{
    visited = 0;
}


Track::~Track()
{
}


Track::Track(char pass_track1, char pass_track2, int station, int opposite)
{
    node_1 = pass_track1;
    node_2 = pass_track2;
    connected_station = station;
    opposite_track = opposite;

    visited = false;
}


Station::Station()
{
}


Station::~Station()
{
}


Station::Station(char pass_station_name, int pass_start, int pass_size)
{
    station_name = pass_station_name;
    track_starting_ID = pass_start;
    track_size = pass_size;
}


SubwaySystem::SubwaySystem()
{
    //Initialize tracks
    //node_1, node_2
    my_track[0] = Track('a', 'b', 1, 1);
    my_track[1] = Track('b', 'a', 0, 0);
    my_track[2] = Track('b', 'c', 2, 6);
    my_track[3] = Track('b', 'd', 3, 8);
    my_track[4] = Track('b', 'e', 4, 10);
    my_track[5] = Track('b', 'f', 5, 15);
    my_track[6] = Track('c', 'b', 1, 2);
    my_track[7] = Track('c', 'e', 4, 11);
    my_track[8] = Track('d', 'b', 1, 3);
    my_track[9] = Track('d', 'e', 4, 12);
    my_track[10] = Track('e', 'b', 1, 4);
    my_track[11] = Track('e', 'c', 2, 7);
    my_track[12] = Track('e', 'd', 3, 9);
    my_track[13] = Track('e', 'g', 6, 17);
    my_track[14] = Track('e', 'h', 7, 19);
    my_track[15] = Track('f', 'b', 1, 5);
    my_track[16] = Track('f', 'h', 7, 20);
    my_track[17] = Track('g', 'e', 4, 13);
    my_track[18] = Track('g', 'k', 10, 28);
    my_track[19] = Track('h', 'e', 4, 14);
    my_track[20] = Track('h', 'f', 5, 16);
    my_track[21] = Track('h', 'i', 8, 24);
    my_track[22] = Track('h', 'j', 9, 26);
    my_track[23] = Track('h', 'k', 10, 29);
    my_track[24] = Track('i', 'h', 7, 21);
    my_track[25] = Track('i', 'k', 10, 30);
    my_track[26] = Track('j', 'h', 7, 22);
    my_track[27] = Track('j', 'k', 10, 30);
    my_track[28] = Track('k', 'g', 6, 18);
    my_track[29] = Track('k', 'h', 7, 23);
    my_track[30] = Track('k', 'i', 8, 25);
    my_track[31] = Track('k', 'j', 9, 27);
    my_track[32] = Track('k', 'l', 11, 33);
    my_track[33] = Track('l', 'k', 10, 32);
    //Initialize stations
    //station_name, track_starting_ID, track_size
    my_station[0] = Station('a', 0, 1);
    my_station[1] = Station('b', 1, 5);
    my_station[2] = Station('c', 6, 2);
    my_station[3] = Station('d', 8, 2);
    my_station[4] = Station('e', 10, 5);
    my_station[5] = Station('f', 15, 2);
    my_station[6] = Station('g', 17, 2);
    my_station[7] = Station('h', 19, 5);
    my_station[8] = Station('i', 24, 2);
    my_station[9] = Station('j', 26, 2);
    my_station[10] = Station('k', 28, 5);
    my_station[11] = Station('l', 33, 1);
    //Initiaize other members
    count_routes = 0;
    Current_Station_ID = 0;
}


SubwaySystem::~SubwaySystem()
{
}



void SubwaySystem::SearchRoute(int Current_Station_ID, int from_track_id, Track **currentPath, int pathCount)
{
    if(my_station[Current_Station_ID].track_starting_ID == 33)
    {
        count_routes++; //Add 1 into the variable “count_routes”
        cout << count_routes << " ";
        for(int i= 0; i < pathCount; i++)
        {
            cout << *currentPath[i]; 
        }
        cout << endl;
        return;
    }
    else //Get into recursive Function Body
    {
        for(int i = my_station[Current_Station_ID].track_starting_ID; i < my_station[Current_Station_ID].track_starting_ID + my_station[Current_Station_ID].track_size; i++)
        {
                    //check all the tracks that we have visited before
            bool visited = false;
            for(int n = 0; n < pathCount; n++)
            {
                if(currentPath[n] == &my_track[i] || i == currentPath[n]->opposite_track) visited = true;
            }


            if(!visited)
            {
                int nextStation = my_track[i].connected_station;
                currentPath[pathCount] = &my_track[i];
                SearchRoute(nextStation, i, currentPath, pathCount + 1); 
            }
        }  
    }
}




ostream& operator<<(ostream& os, const Track& my_track)
{
    os << my_track.node_1 << '.' << my_track.node_2;
    return os;
}

ostream& operator<<(ostream& os, const Station& my_station)
{
    os << my_station.station_name << '.' << my_station.track_starting_ID << '.' << my_station.track_size;
    return os;
}


//This is where the above recursive function SearchRoute goes. I posted it separately so it's easier to read.



// **main**


//#include "subway.h"






int _tmain(int argc, _TCHAR* argv[])
{

    Track *tempTracks[34];
    SubwaySystem findPaths;
    findPaths.SearchRoute(0, -1, tempTracks, 0);

    getchar();

    return 0;
}
//RandomTest.cpp:定义控制台应用程序的入口点。
//
#包括“stdafx.h”
#包括
#包括
使用名称空间std;
班级轨道
{
公众:
//默认构造函数
轨道();
//重载构造函数
轨道(char,char,int车站,int对面);
//析构函数
~Track();
//成员变量
char node_1;//node_1和node_2表示站点(例如
char node_2;//节点_1将是站点A,节点_2将是站点B)
布尔访问;
国际联络站;
int对向轨道;
};
班级站
{
公众:
//默认构造函数
车站();
//析构函数
~Station();
//重载构造函数
车站(字符,整数,整数);
//成员变量
字符站名称;
int track_starting_ID;
int轨道尺寸;
};
等级地铁系统
{
公众:
//默认构造函数
地铁系统();
//析构函数
~SubwaySystem();
//递归函数
无效搜索路径(int);
//其他成员职能
friend ostream&operator我找到了640条路线:

#include <stdio.h>

const char *connectom[] = {
"B",            // A
"ACDEF",        // B
"BE",           // C
"BE",           // D
"CDBGH",        // E
"BH",           // F
"EK",           // G
"EFJKI",        // H
"HK",           // I
"HK",           // J
"HIJGL",        // K
"K"             // L
};

char tracks[0x100];
char strout[0x100];

void path(char x, char *s) {
  *s++ = x;
  if(x == 'L') {
    *s = 0;
    printf("path=%s\n", strout);
  } else {
    for(const char *p = connectom[x - 'A']; *p; p++) {
       unsigned char track_ndx = x > *p? (x << 4) ^ *p : (*p << 4) ^ x;
       if(tracks[track_ndx] == 0) {
         tracks[track_ndx] = 1;
         path(*p, s);
         tracks[track_ndx] = 0;
       } // if
    } // for
  } // else
} // path

int main(int argc, char **argv) {
  path('A', strout);
} // main
#包括
常量字符*connectom[]={
“B”//A
“ACDEF”//B
“BE”//C
“BE”//D
“CDBGH”,//E
“BH”,//F
“EK”,//G
“EFJKI”,//H
“HK”//I
“HK”//J
“HIJGL”,//K
“K”//L
};
字符轨道[0x100];
字符strout[0x100];
无效路径(字符x,字符*s){
*s++=x;
如果(x='L'){
*s=0;
printf(“路径=%s\n”,strout);
}否则{
for(const char*p=connectom[x-'A'];*p;p++){

无符号字符磁道\u ndx=x>*p?(x缩短故事,精简到相关代码,并明确指出错误/问题。1分钟后,这个问题怎么会有2张赞成票?!阅读需要2分钟以上,理解也需要1小时!@MM我也是,再花30分钟理解数学/几何或其他任何东西,我很抱歉。我意识到这一点st非常长。但是我想发布所有我能发布的信息,以便让回答者更清楚(我知道这不是一个单词=)。如果有人可以编辑它,使其成为一个更合适的帖子。我将不胜感激。也感谢您对此进行了投票。这很快。只是一个风格说明。虽然您在声明函数时没有参数的名称,但您应该这样做,因为它使阅读代码的人更清楚这些参数的意图。好的。我认为i--将有助于回溯。问题是,当我尝试实现您的代码版本时,在第一种情况下,当仍然使用当前的_Station_ID时,程序会陷入无限循环。在第二种情况下,使用i时,程序会给出一个巨大的数字。还要确保您在if语句中也使用了i。if(my_track[i]。visted==0)第一种情况下的无限循环将是因为当if语句为false时,CurruntPosixIdID不会被更改。我将把它添加到应答器FROST OFF中,谢谢您试图帮助我。现在程序崩溃了。如果您有C++编译器,如果您在计算机上运行它,检查结果可能会更容易一些。(你不必担心,我愿意测试它)。另外,出于好奇,当我在for循环中递增时,递归调用中的I+1函数会发生什么变化。我注意到我的代码中存在另一个问题。我使用的是同一个计数器(Current_Station_ID)对于大小不同的my_station阵列和my_track阵列。也许您可以帮助我解决这个问题,除非这不重要。编辑:我会再试一次。好的,现在我得到的总路线计数为89,这意味着我们正在接近=).我刚才只得到1。但它仍然不完全正确,因为总的可能路线是640。如果你确定它是640,那么请检查车站和轨道之间的所有链接是否正确。乔,你是有史以来最伟大的人。非常感谢你抽出时间来帮我。我正在尝试看看这是如何工作的现在。我对不断打扰你感到很抱歉,但你是我现在唯一可以求助的人。我有一个问题,为什么你的main中有一个函数getchar()?它在任何地方都没有定义。而且我在尝试打印cout getchar()时不断出错只是为了使控制台窗口不会关闭。您可以将其取出。不确定为什么使用指针会出现错误。尝试打印出对象的部分。例如:cout node_2;哇,很好。这就是
my_track[Current_Station_ID].visited = 1; //mark this track as visited
my_track[Current_Station_ID].node_2 = 1; //mark its corresponding track as visited
cout << my_track[Current_Station_ID].node_1; //save this track
SearchRoute(Current_Station_ID++); <<<<<<<< PROBLEM 
i--; //Backtrack this track  <<<<<<< Also this will do nothing
my_track[Current_Station_ID].visited = 0; <<<<<<< Now Current_Station_ID is 1 more than you are expecting it to be.
my_track[Current_Station_ID].node_2 = 0;//mark its corresponding track as unvisited
void SubwaySystem::SearchRoute(int Current_Station_ID, int from_track_id, Track *currentPath, int pathCount)
{
    if(my_station[Current_Station_ID].track_starting_ID == 33)
    {
        count_routes++; //Add 1 into the variable “count_routes”
        cout << count_routes << " ";
        for(int i= 0; i < pathCount; i++)
        {
             cout << my_track[i]; 
        }
        cout << endl;
        return;
    }
    else //Get into recursive Function Body
    {

         if(from_track_id >= 0) my_track[from_track_id].visited = 1; 

        for(int i = my_station[Current_Station_ID].track_starting_ID; i < my_station[Current_Station_ID].track_starting_ID + my_station[Current_Station_ID].track_size; i++)
        {
            int nextStation = my_track[i].node_2;   ///<<<<<<< But you will need to change node_2 to be an int, and use the station number, not letter when you set them up
            if(my_track[i].visited == 0)
            {
                currentPath[pathCount] = my_track[i];
                SearchRoute(nextStation, i, currentPath, pathCount + 1); 


            }
        }

       if(from_track_id >= 0) my_track[from_track_id].visited = 0; 
    }
}
int main()
{
    Track tempTracks[34];
    SubwaySystem findPaths;
    findPaths.SearchRoute(0, -1, tempTracks, 0);
}
// RandomTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


#include <iostream>
#include <string>
using namespace std;






class Track
{
public:
    //Default Constructor
    Track();

    //Overload Constructor
    Track(char, char, int station, int opposite);

    //Destructor
    ~Track();

    //Member variables
    char node_1;  // node_1 and node_2 represent stations (for example
    char node_2;  // node_1 would be station A and node_2 would be station B)
    bool visited;

    int connected_station;
    int opposite_track;
};

class Station
{
public:
    //Default Constructor
    Station();

    //Destructor
    ~Station();

    //Overload Constructor
    Station(char, int, int);

    //Member variables
    char station_name;
    int track_starting_ID;
    int track_size;
};

class SubwaySystem
{
public:
    //Default Constructor
    SubwaySystem();

    //Destructor
    ~SubwaySystem();

    //Recursive function
    void SearchRoute(int);

    //Other member functions
    friend ostream& operator<<(ostream& os, const Track& my_track);
    friend ostream& operator<<(ostream& os, const Station& my_station);


    //Member variables
    Track my_track[34];
    Station my_station[12];

    int count_routes;
    int Current_Station_ID;

    //String to save found route

    void SearchRoute(int Current_Station_ID, int from_track_id, Track **currentPath, int pathCount);
};





// **cpp**


//#include "subway.h"

using namespace std;

Track::Track()
{
    visited = 0;
}


Track::~Track()
{
}


Track::Track(char pass_track1, char pass_track2, int station, int opposite)
{
    node_1 = pass_track1;
    node_2 = pass_track2;
    connected_station = station;
    opposite_track = opposite;

    visited = false;
}


Station::Station()
{
}


Station::~Station()
{
}


Station::Station(char pass_station_name, int pass_start, int pass_size)
{
    station_name = pass_station_name;
    track_starting_ID = pass_start;
    track_size = pass_size;
}


SubwaySystem::SubwaySystem()
{
    //Initialize tracks
    //node_1, node_2
    my_track[0] = Track('a', 'b', 1, 1);
    my_track[1] = Track('b', 'a', 0, 0);
    my_track[2] = Track('b', 'c', 2, 6);
    my_track[3] = Track('b', 'd', 3, 8);
    my_track[4] = Track('b', 'e', 4, 10);
    my_track[5] = Track('b', 'f', 5, 15);
    my_track[6] = Track('c', 'b', 1, 2);
    my_track[7] = Track('c', 'e', 4, 11);
    my_track[8] = Track('d', 'b', 1, 3);
    my_track[9] = Track('d', 'e', 4, 12);
    my_track[10] = Track('e', 'b', 1, 4);
    my_track[11] = Track('e', 'c', 2, 7);
    my_track[12] = Track('e', 'd', 3, 9);
    my_track[13] = Track('e', 'g', 6, 17);
    my_track[14] = Track('e', 'h', 7, 19);
    my_track[15] = Track('f', 'b', 1, 5);
    my_track[16] = Track('f', 'h', 7, 20);
    my_track[17] = Track('g', 'e', 4, 13);
    my_track[18] = Track('g', 'k', 10, 28);
    my_track[19] = Track('h', 'e', 4, 14);
    my_track[20] = Track('h', 'f', 5, 16);
    my_track[21] = Track('h', 'i', 8, 24);
    my_track[22] = Track('h', 'j', 9, 26);
    my_track[23] = Track('h', 'k', 10, 29);
    my_track[24] = Track('i', 'h', 7, 21);
    my_track[25] = Track('i', 'k', 10, 30);
    my_track[26] = Track('j', 'h', 7, 22);
    my_track[27] = Track('j', 'k', 10, 30);
    my_track[28] = Track('k', 'g', 6, 18);
    my_track[29] = Track('k', 'h', 7, 23);
    my_track[30] = Track('k', 'i', 8, 25);
    my_track[31] = Track('k', 'j', 9, 27);
    my_track[32] = Track('k', 'l', 11, 33);
    my_track[33] = Track('l', 'k', 10, 32);
    //Initialize stations
    //station_name, track_starting_ID, track_size
    my_station[0] = Station('a', 0, 1);
    my_station[1] = Station('b', 1, 5);
    my_station[2] = Station('c', 6, 2);
    my_station[3] = Station('d', 8, 2);
    my_station[4] = Station('e', 10, 5);
    my_station[5] = Station('f', 15, 2);
    my_station[6] = Station('g', 17, 2);
    my_station[7] = Station('h', 19, 5);
    my_station[8] = Station('i', 24, 2);
    my_station[9] = Station('j', 26, 2);
    my_station[10] = Station('k', 28, 5);
    my_station[11] = Station('l', 33, 1);
    //Initiaize other members
    count_routes = 0;
    Current_Station_ID = 0;
}


SubwaySystem::~SubwaySystem()
{
}



void SubwaySystem::SearchRoute(int Current_Station_ID, int from_track_id, Track **currentPath, int pathCount)
{
    if(my_station[Current_Station_ID].track_starting_ID == 33)
    {
        count_routes++; //Add 1 into the variable “count_routes”
        cout << count_routes << " ";
        for(int i= 0; i < pathCount; i++)
        {
            cout << *currentPath[i]; 
        }
        cout << endl;
        return;
    }
    else //Get into recursive Function Body
    {
        for(int i = my_station[Current_Station_ID].track_starting_ID; i < my_station[Current_Station_ID].track_starting_ID + my_station[Current_Station_ID].track_size; i++)
        {
                    //check all the tracks that we have visited before
            bool visited = false;
            for(int n = 0; n < pathCount; n++)
            {
                if(currentPath[n] == &my_track[i] || i == currentPath[n]->opposite_track) visited = true;
            }


            if(!visited)
            {
                int nextStation = my_track[i].connected_station;
                currentPath[pathCount] = &my_track[i];
                SearchRoute(nextStation, i, currentPath, pathCount + 1); 
            }
        }  
    }
}




ostream& operator<<(ostream& os, const Track& my_track)
{
    os << my_track.node_1 << '.' << my_track.node_2;
    return os;
}

ostream& operator<<(ostream& os, const Station& my_station)
{
    os << my_station.station_name << '.' << my_station.track_starting_ID << '.' << my_station.track_size;
    return os;
}


//This is where the above recursive function SearchRoute goes. I posted it separately so it's easier to read.



// **main**


//#include "subway.h"






int _tmain(int argc, _TCHAR* argv[])
{

    Track *tempTracks[34];
    SubwaySystem findPaths;
    findPaths.SearchRoute(0, -1, tempTracks, 0);

    getchar();

    return 0;
}
#include <stdio.h>

const char *connectom[] = {
"B",            // A
"ACDEF",        // B
"BE",           // C
"BE",           // D
"CDBGH",        // E
"BH",           // F
"EK",           // G
"EFJKI",        // H
"HK",           // I
"HK",           // J
"HIJGL",        // K
"K"             // L
};

char tracks[0x100];
char strout[0x100];

void path(char x, char *s) {
  *s++ = x;
  if(x == 'L') {
    *s = 0;
    printf("path=%s\n", strout);
  } else {
    for(const char *p = connectom[x - 'A']; *p; p++) {
       unsigned char track_ndx = x > *p? (x << 4) ^ *p : (*p << 4) ^ x;
       if(tracks[track_ndx] == 0) {
         tracks[track_ndx] = 1;
         path(*p, s);
         tracks[track_ndx] = 0;
       } // if
    } // for
  } // else
} // path

int main(int argc, char **argv) {
  path('A', strout);
} // main