[英]C++ recursive backtracking
I am trying to do recursive backtracking to find a path from point 0 to point 8. I have defined the paths but its goes 0 1 2 and them stops.我正在尝试进行递归回溯以找到从点 0 到点 8 的路径。我已经定义了路径,但它的路径是 0 1 2 并且它们停止了。 Can anyone help?
任何人都可以帮忙吗?
#include <iostream>
#include <vector>
using namespace std;
vector< vector<int> > roads;
void find_path(int Point = 0) {
cout << Point;
int rds = roads.size();
for(int i = 0; i < rds; i++) {
find_path(roads[Point][i]);
}
}
main() {
roads.resize(8);
//VNESUVANJE PATISTA
roads[0].push_back(1);
roads[0].push_back(3);
roads[1].push_back(2);
roads[3].push_back(4);
roads[3].push_back(6);
roads[4].push_back(5);
roads[4].push_back(7);
roads[7].push_back(8);
find_path();
return 0;
}
I did some changes i think now it works properly.我做了一些我认为现在可以正常工作的更改。
#include <iostream>
#include <vector>
using namespace std;
vector< vector<int> > roads;
int path_finded = 0; //Added new variable to know if path is finded.
void find_path(int Point = 0) {
if(Point == 8) { //Checks if the point where we are is 8 and if it is stops the whole thing and chages path_finded to 1
path_finded = 1;
return;
}
int rds = roads[Point].size();//changed roads.size to roads[Point].size so it gives the size of the possible roads from the point where we are.
for(int i = 0; i < rds; i++) {
find_path(roads[Point][i]);
}
return;
}
main() {
roads.resize(8);
//VNESUVANJE PATISTA
roads[0].push_back(1);
roads[0].push_back(3);
roads[1].push_back(2);
roads[3].push_back(4);
roads[3].push_back(6);
roads[4].push_back(5);
roads[4].push_back(7);
roads[7].push_back(8);
find_path();
if(path_finded == 1) cout << "RABOTI"; //prints if it works.
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.