西农数据结构作业_寻找最短路径

 

#include <iostream>
#include <queue>
//猛然发现队列其实可以不用自己写的。。。
//试着用用
using namespace std;
int** map;
int sx, sy, ex, ey;
struct Box {
	int x, y;
	Box() {
	}
	Box(int a, int b) {
		x = a;
		y = b;
	}
};
Box** path;
queue<Box> q;
int direction[8][2] = {
	{-1,0},
	{-1,1},
	{0,1},
	{1,1},
	{1,0},
	{1,-1},
	{0,-1},
	{-1,-1}
};
void findPath();
void printPath();
int main() {
	sx = sy = 0;
	int x, y;
	cin >> x >> y;
	ex = x - 1;
	ey = y - 1;
	map = new int* [x];
	for (int i = 0; i < x; i++) {
		map[i] = new int[y];
	}
	for (int i = 0; i < x; i++) {
		for (int j = 0; j < y; j++) {
			cin >> map[i][j];
		}
	}

	path = new Box * [x];
	for (int i = 0; i < x; i++) {
		path[i] = new Box[y];
	}

	for (int i = 0; i < x; i++) {
		for (int j = 0; j < y; j++) {
			path[i][j] = Box(0, 0);
		}
	}
	findPath();
	printPath();

}

void findPath()
{
	q.push(Box(sx, sy));
	while (!q.empty()) {
		Box temp = q.front();
		q.pop();
		if (temp.x == ex && temp.y == ey)
			return;

		for (int i = 0; i < 8; i++) {
			int tx = temp.x + direction[i][0];
			int ty = temp.y + direction[i][1];
			if (tx >=0 && tx <= ex  && ty >= 0 && ty <=ey && map[tx][ty] == 0) {

				path[tx][ty] = temp;
				q.push(Box(tx, ty));
				map[tx][ty] = 1;
			}
		
		}
	}
}

void printPath()
{
	int a = ex;
	int b = ey;
	cout << "(" << ex + 1 << "," << ey + 1 << ")" << endl;
	while (path[a][b].x != sx || path[a][b].y != sy) {
		cout << "(" << path[a][b].x + 1 << "," << path[a][b].y + 1 << ")" << endl;
		int k = a;
		a = path[a][b].x;
		b = path[k][b].y;
	}
	cout << "(" << sx + 1 << "," << sy + 1 << ")" << endl;
}
//队列其实是不能存路的
//队列为广度优先算法提供基础
//这个最短路径是存放在数组中的
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值