/** * searchNode */ void *searchNode(NodeTree Tree, int key) { NodeTree x; x = Tree; while(x!=NULL && key!=x->key) { if(key<x->key) x = LeftNode(x); else x = RightNode(x); }//while if(x!=NULL) return x->Value; else return NULL; }//searchNode
/* * 算法主搜索函数,Branch-And-Bound Algorithm Search * root 是当前的根结点,已归约,数据完善 */ PATH BABA(NODE root) { int i; static int minDist = INFINITY; static PATH minPath; EDGE selectedEdge; NODE *left, *right; puts("Current Root:\n------------"); ShowMatrix(root.matrix); printf("Root Bound:%d\n", root.bound); /* 如果当前矩阵大小为2,说明还有两条边没有选,而这两条边必定只能有一种组合, * 才能构成整体回路,所以事实上所有路线已经确定。 */ if (MatrixSize(root.matrix, root.path) == 2) { if (root.bound < minDist) { minDist = root.bound; minPath = MendPath(root.path, root.matrix); getch(); return (minPath); } } /* 根据左下界尽量大的原则选分枝边 */ selectedEdge = SelectBestEdge(root.matrix); printf("Selected Edge:(%d, %d)\n", selectedEdge.head + 1, selectedEdge.tail + 1); /* 建立左右分枝结点 */ left = (NODE *)malloc(sizeof(NODE)); right = (NODE *)malloc(sizeof(NODE)); if (left == NULL || right == NULL) { fprintf(stderr,"Error malloc.\n"); exit(-1); } /* 初始化左右分枝结点 */ left->bound = root.bound; /* 继承父结点的下界 */ left->matrix = LeftNode(root.matrix, selectedEdge); /* 删掉分枝边 */ left->path = root.path; /* 继承父结点的路径,没有增加新边 */ left->left = NULL; left->right = NULL; right->bound = root.bound; right->matrix = RightNode(root.matrix, selectedEdge, root.path);/* 删除行列和回路边 */ right->path = AddEdge(selectedEdge, root.path); /* 加入所选边 */ right->left = NULL; right->right = NULL; /* 归约左右分枝结点 */ left->bound += Simplify(&left->matrix); right->bound += Simplify(&right->matrix); /* 链接到根 */ root.left = left; root.right = right; /* 显示到监视器 */ puts("Right Branch:\n------------"); ShowMatrix(right->matrix); puts("Left Branch:\n-----------"); ShowMatrix(left->matrix); /* 如果右结点下界小于当前最佳答案,继续分枝搜索 */ if (right->bound < minDist) { BABA(*right); } /* 否则不搜索,因为这条枝已经不可能产生更佳路线 */ else { printf("Current minDist is %d, ", minDist); printf("Right Branch's Bound(= %d).\n", right->bound); printf("This branch is dead.\n"); } /* 如果右结点下界小于当前最佳答案,继续分枝搜索 */ if (left->bound < minDist) { BABA(*left); } /* 否则不搜索,因为这条枝已经不可能产生更佳路线 */ else { printf("Current minDist is %d, ", minDist); printf("Left Branch's Bound(= %d).\n", left->bound); printf("This branch is dead.\n"); } printf("The best answer now is %d\n", minDist); return (minPath); }