java迷宫最短路径,迷宫最短路径的C++实现(队列:广度优先) | 学步园

#include

#include

#include

using namespace std;

struct point{

int x;

int y;

point *last;//上一步的坐标

};

int main(){

while(1){

int row, col, i, j;

cout<

cin>>row>>col;

int **a = new int* [row+2];

for(i = 0; i < row+2; ++i){

a[i] = new int[col+2];

}

cout<

for(i = 1; i < row+1; ++i){

for(j = 1; j < col+1; ++j){

cin>>a[i][j];

}

}

for(i = 0; i < col+2; ++i){//加墙

a[0][i] = 1;

a[row+1][i] = 1;

}

for(i = 1; i < row+1; ++i){//加墙

a[i][0] = 1;

a[i][col+1] = 1;

}

queue q;

point *start = (point*)malloc(sizeof(point));//起点

cout<

cin>>start->x>>start->y;

start->last = start;

q.push(start);

a[start->x][start->y] = 2;

point end;//终点

cout<

cin>>end.x>>end.y;

int aspect[4][2] = {{0, -1},{0, 1},{-1, 0},{1, 0}};//转向:上下左右

int flag = 0;//是否有路可走的标志

while(!q.empty()){

point *front = q.front();

q.pop();//弹出队头

if(front->x == end.x && front->y == end.y){

flag = 1;

cout<x][front->y]-2<

a[front->x][front->y] = -6;

//cout<x<y;

point *lastPoint = front;

front = front->last;

while((front->x != start->x) || (front->y != start->y)){

//cout<"<x<y;

if(lastPoint->x - front->x == 1){

a[front->x][front->y] = -1;

}else if(lastPoint->x - front->x == -1){

a[front->x][front->y] = -2;

}else if(lastPoint->y - front->y == 1){

a[front->x][front->y] = -3;

}else{

a[front->x][front->y] = -4;

}

lastPoint = front;

front = front->last;

}

//cout<"<x<y<

a[start->x][start->y] = -5;

break;

}else{

for(int i = 0; i < 4 ; ++i){

point *temp = new point;

temp->x = front->x + aspect[i][0];

temp->y = front->y + aspect[i][1];

if(a[temp->x][temp->y] == 0){

temp->last = front;

q.push(temp);

a[temp->x][temp->y] = a[front->x ][front->y] + 1;

}

}

}

}

if(!flag)

cout<

else{

string s[6] = {"★", "☆", "←","→","↑","↓" };

for(int i = 0; i < 11; ++i){

for(int j = 0; j < 10; ++j){

if(a[i][j]==1){

cout<

}else if(a[i][j]<0){

int temp = a[i][j]+6;

cout<

}else{

cout<

}

}

cout<

}

}

system("pause");

}

}

测试数据

9 8

0 0 1 0 0 0 1 0

0 0 1 0 0 0 0 0

0 0 0 0 1 1 1 0

0 1 1 1 0 0 1 0

0 0 0 1 0 0 0 0

0 1 0 0 0 1 0 1

0 1 1 1 1 0 0 1

1 1 0 0 0 0 0 1

0 0 0 0 0 0 0 0

运行结果:

1335278948_9189.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值