gpt4 book ai didi

c++ - 通过组节点的2D vector 进行手动迭代

转载 作者:行者123 更新时间:2023-12-03 07:23:07 24 4
gpt4 key购买 nike

我已经将有向图存储在2D vector 中,并且我想以递归方式遍历所有有向图,从任何有向图通过组从左到右依次遍历。我在下面给出了一个示例,并希望遍历从第一个组(在此示例中为G1)到最后一个组(在此示例中为G3)的所有路径。我已经做了很多尝试,但是我无法构建一个递归来遍历所有路径的任意数量的组。因此,在构建不带递归​​函数调用的手动迭代系统/循环算法时,我需要帮助。对于迭代部分,如果我可以获得可以打印所有可能路径的算法,则将大有帮助。因此,任何来源,技巧和窍门都是有用的。谢谢。graph: enter image description herescript.cpp

#include <iostream>
#include <vector>

using namespace std;

int main() {

vector<int> map = {
{ 1, 2 },
{ 3, 4, 5 },
{ 6, 7 }
};

// Print all paths
// Note :- every array in the map is a group

return 0;
}
output:
1 -> 3 -> 6
1 -> 3 -> 7
1 -> 4 -> 6
1 -> 4 -> 7
1 -> 5 -> 6
1 -> 5 -> 7
2 -> 3 -> 6
2 -> 3 -> 7
2 -> 4 -> 6
2 -> 4 -> 7
2 -> 5 -> 6
2 -> 5 -> 7

最佳答案

#Compile using g++ -std=c++11 code.cpp

#include <iostream>
#include <vector>

using namespace std;


int main() {

vector<vector<int> > map = {
{ 1, 2 },
{ 3, 4, 5 },
{ 6, 7 }
};

vector<int> sizes(map.size());
vector<int> indexes(map.size());
int combinations = 1;

for(int i=0; i<map.size();i++){
sizes[i]=map[i].size();
}

for(int i=0; i<map.size();i++){
combinations*=map[i].size();
}


for(int combination=1; combination <= combinations; combination++){
int multiple = 1;
for(int ind=0; ind<indexes.size(); ind++){
cout << map[ind][indexes[ind]];
if(ind < indexes.size()-1)
cout << " -> ";
}
cout << endl;
for(int j=map.size()-1;j>=0;j--){
multiple*=map[j].size();


indexes[map.size()-1]=combination % map[map.size()-1].size();

if(combination % multiple == 0 && j>0){
//cout << "*";
indexes[j-1] = (indexes[j-1]+1)%map[j-1].size();

}

}
}

return 0;
}




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> 6 -> 17
2 -> 5 -> 7 -> 7 -> 600
2 -> 5 -> 7 -> 7 -> 17
2 -> 5 -> 8 -> 6 -> 600
2 -> 5 -> 8 -> 6 -> 17
2 -> 5 -> 8 -> 7 -> 600
2 -> 5 -> 8 -> 7 -> 17
2 -> 10 -> 6 -> 6 -> 600
2 -> 10 -> 6 -> 6 -> 17
2 -> 10 -> 6 -> 7 -> 600
2 -> 10 -> 6 -> 7 -> 17
2 -> 10 -> 7 -> 6 -> 600
2 -> 10 -> 7 -> 6 -> 17
2 -> 10 -> 7 -> 7 -> 600
2 -> 10 -> 7 -> 7 -> 17
2 -> 10 -> 8 -> 6 -> 600
2 -> 10 -> 8 -> 6 -> 17
2 -> 10 -> 8 -> 7 -> 600
2 -> 10 -> 8 -> 7 -> 17
2 -> 100 -> 6 -> 6 -> 600
2 -> 100 -> 6 -> 6 -> 17
2 -> 100 -> 6 -> 7 -> 600
2 -> 100 -> 6 -> 7 -> 17
2 -> 100 -> 7 -> 6 -> 600
2 -> 100 -> 7 -> 6 -> 17
2 -> 100 -> 7 -> 7 -> 600
2 -> 100 -> 7 -> 7 -> 17
2 -> 100 -> 8 -> 6 -> 600
2 -> 100 -> 8 -> 6 -> 17
2 -> 100 -> 8 -> 7 -> 600
2 -> 100 -> 8 -> 7 -> 17

关于c++ - 通过组节点的2D vector 进行手动迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64491875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com