最优工程布线问题之分支界限法(bfs)
#include<iostream>
#include<queue>
#include<iomanip>
using namespace std;
typedef struct{
int x;
int y;
}Position;
int graph[100][100];
void init(int m,int n);
bool findPath(Position s,Position e,Position*&road,int &Len);
int main(void){
Position startPoint,endPoint;
Position *road;
int Len,m,n;
cout<<"请输入方阵大小M行n列:输入格式m n\n";
cin>>m>>n;
init(m,n);
while(!(m==0&&n==0)){
cout<<"输入障碍物坐标x,y(输入 0 0 结束)\n";
cin>>m>>n;
graph[m][n]=-2;
}
cout<<"请输入起点\n";
cin>>startPoint.x>>startPoint.y;
cout<<"请输入终点\n";
cin>>endPoint.x>>endPoint.y;
if(findPath(startPoint,endPoint,road,Len)){
cout<<"最短路长度为:"<<Len<<endl;
cout<<"路线为:\n";
for(int i=0;i<Len;i++){
cout<<"["<<road[i].x<<","<<road[i].y<<"] ";
}
cout<<endl;
}else{
cout<<"没有找到有效路径\n";
}
return 0;
}
void init(int m,int n){
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
graph[i][j]=-1;
}
}
for(int i=0;i<=n+1;i++){
graph[0][i]=graph[m+1][i]=-2;
}
for(int i=0;i<=m+1;i++){
graph[i][0]=graph[i][n+1]=-2;
}
}
bool findPath(Position s,Position e,Position*&road,int &Len){
if((s.x==e.x)&&(s.y==e.y)){
Len=0;
return true;
}
Position DIR[4];
Position here,next;
DIR[0].x=0;
DIR[0].y=1;
DIR[1].x=1;
DIR[1].y=0;
DIR[2].x=0;
DIR[2].y=-1;
DIR[3].x=-1;
DIR[3].y=0;
here=s;
graph[here.x][here.y]=0;
queue<Position>Queue;
while(1){
for(int i=0;i<4;i++){
next.x=here.x+DIR[i].x;
next.y=here.y+DIR[i].y;
if(graph[next.x][next.y]==-1){
graph[next.x][next.y]=graph[here.x][here.y]+1;
Queue.push(next);
}
if((next.x==e.x)&&(next.y==e.y)){
break;
}
}
if((next.x==e.x)&&(next.y==e.y)){
break;
}
if(Queue.empty()){
return false;
}else{
here=Queue.front();
Queue.pop();
}
}
Len=graph[e.x][e.y];
road=new Position[Len];
here=e;
for(int i=Len-1;i>=0;i--){
road[i]=here;
for(int j=0;j<4;j++){
next.x=here.x+DIR[j].x;
next.y=here.y+DIR[j].y;
if(graph[next.x][next.y]==i){
break;
}
}
here=next;
}
return true;
}
测试样例
请输入方阵大小M行n列:输入格式m n
5 6
输入障碍物坐标x,y(输入 0 0 结束)
1 6
输入障碍物坐标x,y(输入 0 0 结束)
2 3
输入障碍物坐标x,y(输入 0 0 结束)
3 4
输入障碍物坐标x,y(输入 0 0 结束)
3 5
输入障碍物坐标x,y(输入 0 0 结束)
5 1
输入障碍物坐标x,y(输入 0 0 结束)
0 0
请输入起点
2 1
请输入终点
4 6
最短路长度为:7
路线为:
[3,1] [4,1] [4,2] [4,3] [4,4] [4,5] [4,6]