运用分支限界法解决布线问题

#include <stdio.h>
typedef struct {
  int row;
  int col; 
}Position;
int FindPath (Position start, Position finish, int &PathLen, Position *&path)
{ //计算从起始位置start到目标位置finish的最短布线路径,找到返回1,否则,返回0
  int  i;
  if ((start.row = = finish.row) && (start.col = = finish.col)) {
PathLen = 0;   return 0; } //start = finish
  //设置方格阵列”围墙”
  for (i = 0; i <= m+1; i++)
grid[0][i] = grid[n+1][i] = 1; //顶部和底部
  for (i = 0; i <= n+1; i++)
grid[i][0] = grid[i][m+1] = 1; //左翼和右翼
  //初始化相对位移
int  NumOfNbrs = 4; //相邻方格数
  Position offset[4], here, nbr;
  offset[0].row = 0;   offset[0].col = 1;   //右
  offset[0].row = 1;   offset[0].col = 0;   //下
  offset[0].row = 0;   offset[0].col = -1;  //左
  offset[0].row = -1;  offset[0].row = 0;  //上
  here.row = start.row;
  here.col = start.col;
  LinkedQueue <Position> Q; //标记可达方格位置
  do {
for (i = 0; i< NumOfNbrs; i++) { //标记可达相邻方格
nbr.row = here.row + offset[i].row ;
nbr.col = here.col + offset[i].col;
if (grid[nbr.row][nbr.col] = = 0) { //该方格未标记
  grid[nbr.row][nbr.col] = grid[here.row][here.col] + 1;
if ((nbr.row = = finish.row) && (nbr.col = = finish.col))  break;//完成布线
Q.Add(nbr);  
       }
}
if ((nbr.row = = finishi.row) && (nbr.col = = finish.col))  break;//完成布线
if (Q.IsEmpty()) //活队列是否为空
return 0; //无解
      Q.delete(here); //取下一个扩展结点
}while (1);
//构造最短布线路径
PathLen = grid[finish.row][finish.col] - 2;
path = new Position[PathLen];
here = finish;
for (int j = PathLen – 1; j >= 0; j--) { //找前驱位置
  path[j] = here;
  for (i = 0; i< NumOfNbrs; i++) {
nbr.row = here.row + offset[i].row ;
nbr.col = here.col + offset[i].col;
if (grid[nbr.row][nbr.col] = = j+2)  break;
}
  here = nbr; //向前移动
  }
return 1;
}
void main ()
{
  int grid[8][8];
  int PathLen, *path;
  Position start, finish;
  start.row = 3;  start.col = 2;
  finish.row = 4; finish.col = 6;

  FindPath (start, finish, PathLen, path);
 }

    原文作者:分支限界法
    原文地址: https://blog.csdn.net/qq_16151611/article/details/41862575
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞