常见带障碍迷宫最短路径

#include <iostream>
#include <queue>
#include <stdlib.h>
using namespace std;
#define OBJECT -2
#define WALL 1
typedef struct{
	int x,y,preX,preY,val;
}Node;

int step[50][50];//标识是否走过 

//广度优先遍历找最短路径 
Node bfs(Node **map, int n, int m){
	int direc[][2] = {{-1,0},{0,-1},{1,0},{0,1}};//控制四个方向 
	map[0][0].preX = -1;map[0][0].preY = -1;
	queue<Node> q;
	q.push(map[0][0]);
	while(!q.empty()){ //广度优先暴搜 
		Node cur = q.front();
		for(int i = 0;i<4;i++){
			int nextX = cur.x + direc[i][0];
			int nextY = cur.y + direc[i][1];
			if(nextX>=0 && nextX <m && nextY>=0 && nextY <n){//判断越界 
				if(map[nextX][nextY].val == OBJECT){
					map[nextX][nextY].preX = cur.x;
					map[nextX][nextY].preY = cur.y;
					return map[nextX][nextY];
				}else if(!step[nextX][nextY] && map[nextX][nextY].val != WALL){
					map[nextX][nextY].preX = cur.x;
					map[nextX][nextY].preY = cur.y;
					q.push(map[nextX][nextY]);
					step[nextX][nextY] = 1;
				}
			}
		}
		q.pop();
	}
	Node empty;
	return empty;
}

int main(){
	int n,m;
	cin>>n>>m;
	Node **map = (Node **)malloc(sizeof(Node*)*n);
	for(int i = 0;i<n;i++){
		map[i] = (Node *)malloc(sizeof(Node)*m);
	}
	for(int i = 0;i<n;i++){
		for(int j = 0;j<m;j++){
			int val;
			cin>>val;
			map[i][j].val = val;
			map[i][j].x = i;
			map[i][j].y = j;
		}
	}
	
	Node object = bfs(map,n,m);
	cout<<object.x<<","<<object.y<<endl;
	int xx = object.preX;
	int yy = object.preY;
	while(xx!=0 || yy!=0){
		cout<<xx<<","<<yy<<" -> ";
		object = map[xx][yy];
		xx = object.preX;
		yy = object.preY;
	}
	cout<<"0,0"<<endl;
	return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值