【宽度优先搜索笔记】BFS输出最短路径_最短路径

【宽度优先搜索笔记】BFS输出最短路径_#include_02

核心思路:用pre数组存放当前选择的前一个选择(即cur变量),然后调用递归函数打印

例:输出迷宫最短路径坐标

0010

1000

n*m迷宫,0表示路,1表示墙,从左上角走到右下角,假设最短路径唯一,输出最短路径

用pre[n][m]保存当前位置的上一个位置,递归输出

代码:

#include<iostream>
#include<queue>
using namespace std;
struct node {
	int x, y;
	node(int _x, int _y) {
		x = _x;
		y = _y;
	}
	node() {
	};
};
int G[10][10];
bool vis[10][10];
node pre[10][10];
int n, m;
bool judge(int i, int j) {
	if (vis[i][j] == true || G[i][j] == 1 || !(i >= 1 && i <= n && j >= 1 && j <= m))
		return false;
	return true;
}
void print(int x, int y) {
	if (x == 1 && y == 1) {
		cout << "(" << x << "," << y << ")" << endl;
		return;
	}
	node temp = pre[x][y];
	print(temp.x, temp.y);
	cout << "(" << x << "," << y << ")" << endl;
	return;
}
void bfs(node temp) {
	queue<node>q;
	q.push(temp);
	while (!q.empty()) {
		node cur = q.front();
		q.pop();
		int x = cur.x;
		int y = cur.y;
		vis[x][y] = true;
		if (x == n && y == m) {
			print(x, y);
			return;
		}

		if (judge(x + 1, y)) {
			pre[x + 1][y] = node(x, y);
			vis[x + 1][y] = true;
			q.push(node(x + 1, y));
		}
		if (judge(x - 1, y)) {
			pre[x - 1][y] = node(x, y);
			vis[x - 1][y] = true;
			q.push(node(x - 1, y));
		}
		if (judge(x, y - 1)) {
			pre[x][y - 1] = node(x, y);
			vis[x][y - 1] = true;
			q.push(node(x, y-1));
		}
		if (judge(x, y + 1)) {
			pre[x][y + 1] = node(x, y);
			vis[x][y + 1] = true;
			q.push(node(x, y + 1));
		}

	}
}
void input()
{
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> G[i][j];
		}
	}
}
int main() {
	input();
	node temp(1, 1);
	bfs(temp);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.