您的位置:首页 > 其它

电路布线问题

2016-10-06 22:28 197 查看
1、问题描述:从起点到终点所走过的最短路线。
分析:用到队列来进行存储。
2、代码实现
因为要用到队列,所以用C++实现更好。
#include<iostream>
#include<queue>
#include<time.h>
#include<ctype.h>
using namespace std;

#define ROW_COUNT    8
#define COL_COUNT    8

#define WALL        1
#define NOT_WALL    0

#define WALL_COUNT    16

typedef struct POS{
int x;  //行
int y;  //列
bool operator==(const POS &pos){  //对==运算符的重载
return (x==pos.x && y==pos.y);
}
}POS;

void initmap(int (*map)[COL_COUNT], int count); //初始化图
void showmap(int (*map)[COL_COUNT], int row, int col); //显示图
bool findPath(int (*map)[COL_COUNT], POS start, POS end, int &pathlen, POS *&path);//寻找最短路径

bool findPath(int (*map)[COL_COUNT], POS start, POS end, int &pathlen, POS *&path){
if(start == end){
pathlen = 0;
return true;
}
POS curpos = start;
int NumOfnbr = 4;
queue<POS> Q;

POS offset[4]; //控制方向
offset[0].x = 0; offset[0].y = 1;  //right
offset[1].x = 1; offset[1].y = 0;  //down
offset[2].x = 0; offset[2].y = -1; //left
offset[3].x = -1; offset[3].y = 0; //up

map[curpos.x][curpos.y] = 2; //起点初始化为2
POS nbr; //邻接点
do{
for(int i = 0; i < NumOfnbr; i++){
nbr.x = curpos.x + offset[i].x;  //right
nbr.y = curpos.y + offset[i].y;
if(map[nbr.x][nbr.y] == 0){
map[nbr.x][nbr.y] = map[curpos.x][curpos.y]+1;
if(nbr == end)
break;
Q.push(nbr);
}
}

if(nbr == end){
break;
}
if(Q.empty()){
return false;
}
curpos = Q.front();
Q.pop();
}while(true);

pathlen = map[end.x][end.y] - 2; //画出模型才能看出
path = new POS[pathlen];
curpos = end;
for(int j = pathlen-1; j >= 0; j--){
path[j] = curpos;
for(int i = 0; i < NumOfnbr; i++)
{
nbr.x = curpos.x + offset[i].x;
nbr.y = curpos.y + offset[i].y;
if(map[nbr.x][nbr.y] == j+2)
break;
}
curpos = nbr;
}
return true;
}

void showmap(int (*map)[COL_COUNT], int row, int col){
int i;
int j;

for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
cout<<map[i][j]<<" ";
}
cout<<endl;
}
}

void initmap(int (*map)[COL_COUNT], int count){
int i;
int index;

srand(time(NULL));
for(i = 0; i < WALL_COUNT; i++){
index = rand()%count;
if(map[0][index] != WALL){
map[0][index] = WALL;
}

}
}

int main(void){
int map[ROW_COUNT][COL_COUNT] = {0};
POS start = {1, 0};
POS end = {7, 7};
int pathlen = 0;
POS *path;

initmap(map, ROW_COUNT*COL_COUNT);
showmap(map, ROW_COUNT, COL_COUNT);
bool flag = findPath(map, start, end, pathlen, path);

if(flag){
cout<<"pathlen = "<<pathlen<<endl;
for(int i = 0; i < pathlen; i++){
cout<<path[i].x<<","<<path[i].y<<endl;
}
}else{
cout<<"No Path."<<endl;
}

cout<<"------------------------------------"<<endl;
showmap(map, ROW_COUNT, COL_COUNT);
return 0;
}
运行结果




最后的那个图就是所找的具体情况图了;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  布线 队列 电路