草庐IT

c++ - 实现功能的麻烦(递归)

coder 2024-02-21 原文

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

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

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

 void SubwaySystem::SearchRoute(int Current_Station_ID)
{
        if(my_station[Current_Station_ID].track_starting_ID == 33)  // Find a successful route to Station L.
//The condition is set to check for 33 because a track_starting_ID of 33 would correspond to station L.
        {
            count_routes++; //Add 1 into the variable “count_routes”
            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
                {
                    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++); //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
                }
            }
        }
    }
}

让我解释一下变量代表什么:
Current_Station_ID 基本上是一个类似 i 的计数器。
my_station 是一个大小为 12 的数组,它包含所有 12 个站。
my_track 是一个大小为 34 的数组,其中包含每个站点之间所有可能的轨道组合。
track_starting_ID 表示某个站点的可能轨道在 my_track 数组中开始的位置。抱歉,我不确定如何用更好的方式来表达这一点。例如,如果您在帖子底部的整个代码部分中引用我在 SubwaySystem 构造函数中初始化的车站数组和轨道数组。可以看到track_starting_ID是指某站轨道的起始位置。即 starting_ID 为 0 对应于 my_track[0],它是从站“A”开始的轨道的开始,而 starting_ID 为 1 指的是 my_track(1),它是从站“B”开始的轨道的开始。 starting_ID 为 6 对应于位置 [6] 的 my_track 数组中从站“C”开始的轨道。等等。 (希望这能让它更清晰而不是更困惑)。
track_size 表示从图片中可以看到每个站点发出的轨道数。例如,B 站的轨道大小为 5,因为 B 站有 5 条轨道。
visitednode_1node_2 是不言自明的。 visited 是一个 bool 变量,它检查一个站点是否被访问过,节点分别是当前轨道两侧的站点。

问题是我不知道如何修复函数以进行递归。几天前我和我的助教讨论过这个问题,我告诉他我想用我的职能完成什么。我们一起编写了一些伪代码,以便更清楚地了解我尝试编写的函数的目标是什么,我已提供:

SearchRoute(int Current_Station_ID)
{ 
     if ( ) //Find a successful route to Station L 
     { 
         … //Add 1 into the variable “count_routes” 
         … //Print out this route 
         return; 
     } 
     else //Get into recursive Function Body 
     { 
         //Use the track array to get all of its connected stations 
         for(int i = starting_ID; i < starting_ID + current size; i++) 
         { 
             if() // if this track is not visited before 
             { 
                 … //mark this track as visited 
                 … //mark its corresponding track as visited 
                 … //save this track 
                 SearchRoute( nextStaton_ID); // Recursive 
                 … //Backtrack this track 
                 … //mark this track as unvisited 
                 … //mark its corresponding track as unvisited 
             } 
         } 
     } 
} 

这就是我对问题的理解:我似乎无法正确实现我的递归函数 SearchRoute,因为我需要打印路径、标记路径,然后再次取消标记路径以允许回溯。当我打印出最终结果时,我要么陷入无限循环,要么得到一条轨道,例如 A 到 B,具体取决于我尝试放入递归调用本身的内容。

为了清楚起见,这是我在上面发布的不包括递归部分的整个程序:

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

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


Track::~Track()
{
}


Track::Track(char pass_track1, char pass_track2)
{
    node_1 = pass_track1;
    node_2 = pass_track2;
    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');
    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;
}


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()
{
    SubwaySystem findPaths;
    findPaths.SearchRoute(0);
}

最佳答案

好的,这是一个可行的解决方案,它给出了 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;
}

关于c++ - 实现功能的麻烦(递归),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505038/

有关c++ - 实现功能的麻烦(递归)的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  3. ruby-on-rails - Cucumber 是否只是 rspec 的包装器以帮助将测试组织成功能? - 2

    只是想确保我理解了事情。据我目前收集到的信息,Cucumber只是一个“包装器”,或者是一种通过将事物分类为功能和步骤来组织测试的好方法,其中实际的单元测试处于步骤阶段。它允许您根据事物的工作方式组织您的测试。对吗? 最佳答案 有点。它是一种组织测试的方式,但不仅如此。它的行为就像最初的Rails集成测试一样,但更易于使用。这里最大的好处是您的session在整个Scenario中保持透明。关于Cucumber的另一件事是您(应该)从使用您的代码的浏览器或客户端的角度进行测试。如果您愿意,您可以使用步骤来构建对象和设置状态,但通常您

  4. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  5. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  6. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  7. MIMO-OFDM无线通信技术及MATLAB实现(1)无线信道:传播和衰落 - 2

     MIMO技术的优缺点优点通过下面三个增益来总体概括:阵列增益。阵列增益是指由于接收机通过对接收信号的相干合并而活得的平均SNR的提高。在发射机不知道信道信息的情况下,MIMO系统可以获得的阵列增益与接收天线数成正比复用增益。在采用空间复用方案的MIMO系统中,可以获得复用增益,即信道容量成倍增加。信道容量的增加与min(Nt,Nr)成正比分集增益。在采用空间分集方案的MIMO系统中,可以获得分集增益,即可靠性性能的改善。分集增益用独立衰落支路数来描述,即分集指数。在使用了空时编码的MIMO系统中,由于接收天线或发射天线之间的间距较远,可认为它们各自的大尺度衰落是相互独立的,因此分布式MIMO

  8. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  9. ruby - Arrays Sets 和 SortedSets 在 Ruby 中是如何实现的 - 2

    通常,数组被实现为内存块,集合被实现为HashMap,有序集合被实现为跳跃列表。在Ruby中也是如此吗?我正在尝试从性能和内存占用方面评估Ruby中不同容器的使用情况 最佳答案 数组是Ruby核心库的一部分。每个Ruby实现都有自己的数组实现。Ruby语言规范只规定了Ruby数组的行为,并没有规定任何特定的实现策略。它甚至没有指定任何会强制或至少建议特定实现策略的性能约束。然而,大多数Rubyist对数组的性能特征有一些期望,这会迫使不符合它们的实现变得默默无闻,因为实际上没有人会使用它:插入、前置或追加以及删除元素的最坏情况步骤复

  10. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

随机推荐