小程序:递归广度有限求最短路径_拔剑-浆糊的传说_新浪博客


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

struct node
{
node(node* left1 = NULL, node* right1 = NULL, const int l_cost1 = 0, const int r_cost1 = 0, const string& name1 = "")
:left(left1), right(right1), l_cost(l_cost1), r_cost(r_cost1), name(name1)
{
}

node* left;
int       l_cost;

node* right;
int       r_cost;
string  name;
};

int best_cost = 9999999;
vector<  vector* > pathes;
vector *                 best_path = NULL;

// 采用递归方式求取最近距离!
void find_best_J(node* pnode, int cost, vector*  path, const node* pDest)
{
cout << cost << endl;

if (pnode == pDest)
{
if (cost < best_cost)
{
best_cost = cost;
best_path = path;
}
return;
}

if (pnode->left  && pnode->right)
{
vector* p1 = new vector(*path);
vector* p2 = new vector(*path);
p1->push_back(pnode->left);
p2->push_back(pnode->right);

pathes.push_back(p1);
pathes.push_back(p2);

find_best_J(pnode->left, cost + pnode->l_cost, p1, pDest);
find_best_J(pnode->right, cost + pnode->r_cost, p2, pDest);
//cout << "new cost left = " << cost + pnode->l_cost << endl;
//cout << "new cost right = " << cost + pnode->r_cost << endl;
}
else
{
node* pp = (pnode->left) ? (pnode->left) : (pnode->right);
int cost_new = cost +  ((pnode->left) ? (pp->l_cost) : (pp->r_cost));
//cout << "new cost = " << cost_new << endl;
path->push_back(pp);
find_best_J(pp, cost_new, path, pDest);
}
}

int main()
{

// directly use local object to represent a network, in real case, you need dynamically allocate object
// or using array or file to control to network generation
//
//   A  B   20
//   A  C   25
//   B  E   30
// ...
node J(NULL, NULL, 0, 0, "J");

node G(&J, NULL, 10, 0, "G");
node H(NULL, &J, 0, 35, "H");

node D(&G, NULL, 40, 0, "D");
node E(&H, &G, 25, 5, "E");
node F(NULL, &H, 0, 30, "F");

node B(&E, &D, 30, 10, "B");
node C(&F, &E, 15, 55, "C");

node A(&B, &C, 25, 20, "A");
//-------------------------------------------------------------


vector* p1 = new vector();
p1->push_back(&A);
pathes.push_back(p1);
find_best_J(&A, 0, p1, &J);

for (auto& node1 : *best_path)
{
cout << node1->name << " ";
}
cout << endl;

// delete memory
for (auto& path : pathes)
{
delete path;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值