0

AからLまでの駅がある地下鉄システムで可能なすべてのパスを印刷しようとしています。つまり、目的は、人が線路を越えずに地下鉄システムを通過するためにいくつのルートをたどることができるかを見つけることです。一度より。以前に C で隣接行列を使用してこのプログラムを作成したので、640 の可能なパスがあることを知っています。現在、隣接行列を使用せずに C++ でクラスを使用することを除いて、同じプログラムを作成しようとしています。

私が抱えている問題は、再帰関数 SearchRoute を適切に実装できないように見えることです。これは、パスを出力し、パスにフラグを立ててから、バックトラッキングを可能にするためにパスのフラグを再度外す必要があるためです。最終結果を印刷すると、A から B へのトラックしか得られません。これは、明らかに何かが間違っていることを意味します。

これが私が問題だと信じていることです: SubwaySystem::SearchRoute 関数で、再帰関数の呼び出しを明らかに許可しない if ステートメントと else ステートメントを使用していることはわかっていますが、else の代わりに別の if ステートメントを入れようとしましたが、どのような状態になるかはよくわかりません。

void SubwaySystem::SearchRoute(int Current_Station_ID)
{
    while(Current_Station_ID < 33)
    {
        cout << "In while loop\n";
        // \\ Checking progress
        if(Current_Station_ID == 0)  //Find a successful route to Station L
        {
            count_routes++; //Add 1 into the variable “count_routes”
            cout << "In if statement\n";
            // \\Checking progress
            cout << count_routes << " " << my_track[Current_Station_ID] << endl; //Print out this route
            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++)
            {
                if(my_track[Current_Station_ID].visited == 0)  //if this track is not visited before
                {
                    cout << "In recursive part of function\n";
                    // \\ Checking progress
                    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] << endl; //save this track
                    SearchRoute(Current_Station_ID + 1); //Recursive
                    i--; //Backtrack this track
                    my_track[Current_Station_ID].visited = 0;//mark this track as unvisited
                    my_track[Current_Station_ID].node_2 = 0;//mark its corresponding track as unvisited
                }
            }
        }
    }
}

また、プログラム全体の進捗状況を追跡するために、途中で印刷ステートメントを入れてみました. 私の再帰関数は、上で指定した理由で呼び出されることはありません(少なくとも、それが機能していないと思う理由です)。そして、何らかの理由で、デフォルトおよびオーバーロードのトラック コンストラクターが何度も呼び出される理由がわかりません。

私のコードの問題点を見つけ出し、正しい方法を教えていただければ幸いです。私はこれについて考えるのにうんざりしています。前もって感謝します。

単一の TU 内の残りのプログラムは次のとおりです。

//Function Declarations
#include <iostream>
#include <string>

using namespace std;

#ifndef SUBWAY_H
#define SUBWAY_H

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

    //Overload Constructor
    Track(char, char);

    //Destructor
    ~Track();

    //Member variables
    char node_1;
    char node_2;
    bool visited;
};

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
};

#endif

// **cpp**

//Function Definitions
#include <iostream>
#include <string>

//#include "subway.h"

using namespace std;

Track::Track()
{
    visited = 0;
    //cout << "Default Track has been called\n";
    //\\ Checking progress
}


Track::~Track()
{
}


Track::Track(char pass_track1, char pass_track2)
{
    node_1 = pass_track1;
    node_2 = pass_track2;
    visited = false;
    //cout << "Overload Track constructor has been called\n";
    // \\ Checking progress
}


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;
    //cout << "Overload station has been called\n";
    // \\ Checking progress
}


SubwaySystem::SubwaySystem()
{
    //Initialize tracks
    //node_1, node_2
    my_track[0] = Track('a', 'b');
    my_track[1] = Track('b', 'a');
    my_track[2] = Track('b', 'c');
    my_track[3] = Track('b', 'd');
    my_track[4] = Track('b', 'e');
    my_track[5] = Track('b', 'f');
    my_track[6] = Track('c', 'b');
    my_track[7] = Track('c', 'e');
    my_track[8] = Track('d', 'b');
    my_track[9] = Track('d', 'e');
    my_track[10] = Track('e', 'b');
    my_track[11] = Track('e', 'c');
    my_track[12] = Track('e', 'd');
    my_track[13] = Track('e', 'g');
    my_track[14] = Track('e', 'h');
    my_track[15] = Track('f', 'b');
    my_track[16] = Track('f', 'h');
    my_track[17] = Track('g', 'e');
    my_track[18] = Track('g', 'k');
    my_track[19] = Track('h', 'e');
    my_track[20] = Track('h', 'f');
    my_track[21] = Track('h', 'i');
    my_track[22] = Track('h', 'j');
    my_track[23] = Track('h', 'k');
    my_track[24] = Track('i', 'h');
    my_track[25] = Track('i', 'k');
    my_track[26] = Track('j', 'h');
    my_track[27] = Track('j', 'k');
    my_track[28] = Track('k', 'g');
    my_track[29] = Track('k', 'h');
    my_track[30] = Track('k', 'i');
    my_track[31] = Track('k', 'j');
    my_track[32] = Track('k', 'l');
    my_track[33] = Track('l', 'k');
    //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;
    //cout << "SubwaySystem constructor called\n";
    // \\ Checking progress
}


SubwaySystem::~SubwaySystem()
{
}

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 <iostream>
#include <string>

//#include "subway.h"

using namespace std;

int main(int argc, char **argv)
{
    SubwaySystem Test;
    Test.SearchRoute(0);
}

「進行状況を確認しています」の印刷ステートメントがコードを読みにくくしている場合は申し訳ありません。

4

2 に答える 2

1

再帰に入ることはありません:

// this method is called with value 0
void SubwaySystem::SearchRoute(int Current_Station_ID)
{
    while(Current_Station_ID < 33)
    {
        cout << "In while loop\n";
        // \\ Checking progress
        if(Current_Station_ID == 0)  //Find a successful route to Station L
        {
            count_routes++; //Add 1 into the variable “count_routes”
            cout << "In if statement\n";
            // \\Checking progress
            cout << count_routes << " " << my_track[Current_Station_ID] << endl; //Print out this route
            return; // ERROR: here you return from the very 1st method call, breaking the search
        }
于 2013-10-20T03:32:02.190 に答える
0

基本的にあなたのためにコードを書くことなく、私はこれを提案します:

再帰関数には while ステートメントを含めるべきではありません (再帰関数の要点は、それ自体が一種の while ステートメントであるということです)。

再帰関数の最初のことは、ステーション ID が 'L' ステーションのすぐ隣にあるかどうか、または使用する唯一のパスが既に使用されているかどうかを確認することです。隣接している場合は、その駅から L までの線路があることを返すことができます。

そうでない場合は、まだ移動していない隣接するすべてのステーションに対して再帰関数を呼び出し、その結果をその時点でいるステーションの計算の一部として使用します。

データに基づく例で明確にするには:

  1. まず、'a' をパラメーターとして関数を呼び出します。
  2. 関数の最初のチェックでは、'a' に 'l' へのパスがあるかどうかがチェックされます (そうでないため、関数は戻りません)。
  3. この関数は、現在のステーション「a」からのパスを持つすべてのステーションを再帰的に呼び出します。('b'のみ)
  4. 'b' から 'l' への直接のトラックはまだないため、関数は今度は 'a'、'c'、'd'、'e'、'f' で自分自身を呼び出し続けます。
  5. 'a' を使用した関数への新しい呼び出しから、最初のチェックで、'b' への唯一の使用可能なルートが既に使用されていることが検出されるため、否定応答が返され、何も出力されません。
  6. ステーションを指定して関数を呼び出したときに、'l' への直接のパスがあることを検出すると、そのパス セグメントを出力 (または保存) し、true を返す必要があります。
  7. 再帰関数は、独自の再帰呼び出しからすべての結果を収集し、それらのステーションの結果にパスを追加します。
  8. 正確な実装は、プログラムから必要な出力によって異なります。すべてのパスを出力する必要がある場合は、有効なパスのリストを保持し、新しい分岐 (複数の接続ステーション) が発生するたびにパスを追加し、再帰関数から負の戻り値を受け取ったときにパスを削除できます。最後の呼び出しが返ってきたら、収集したパスを印刷できます。

それは物事を明確にしますか?

于 2013-10-21T08:11:01.103 に答える