BFS--宽搜求最短路径

10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#

#是障碍,.是通道,S是起点,G是终点

求出最短路径长度和路径

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<queue>
#include<cstdio>

using namespace std;

typedef pair<int, int> P;

const int MAX_N = 105;
const int MAX_M = 105;

char field[MAX_N][MAX_M];
bool Visited[MAX_N][MAX_M];
int PathLength[MAX_N][MAX_M];
P Pre[MAX_N][MAX_M];

int N, M;
int sx, sy;
int dx, dy;

int Dir[4][2] = { 1,0,-1,0,0,1,0,-1 };

int bfs()
{
	memset(Visited, false, sizeof(Visited));
	memset(PathLength, 0, sizeof(PathLength));
	queue<P> q;
	q.push(P(sx, sy));
	Visited[sx][sy] = true;
	while (!q.empty()) {
		P p = q.front(); q.pop();
		if (p.first == dx && p.second == dy) {
			break;
		}
		for (int i = 0; i < 4; i++) {
			int nx = p.first + Dir[i][0];
			int ny = p.second + Dir[i][1];
			if (nx >= 0 && nx < N && ny >= 0 && ny < M && !Visited[nx][ny] && field[nx][ny] != '#') {
				q.push(P(nx, ny));
				Visited[nx][ny] = true;
				PathLength[nx][ny] = PathLength[p.first][p.second] + 1;
				Pre[nx][ny] = P(p.first, p.second);
			}
		}
	}
	return PathLength[dx][dy];
}

void Print(P Cur) {
	if (Cur.first == sx && Cur.second == sy) {
		cout << "(" << sx << "," << sy << ")" << endl;
		return;
	}
	Print(Pre[Cur.first][Cur.second]);
	cout << "(" << Cur.first << "," << Cur.second << ")" << endl;
}

int main() {
	scanf("%d%d", &N, &M);
	for (int i = 0; i < N; i++) {
		scanf("%s", &field[i]);
		for (int j = 0; j < M; j++) {
			if (field[i][j] == 'S') {
				sx = i;sy = j;
			}
			if (field[i][j] == 'G') {
				dx = i; dy = j;
			}
		}
	}
	int Result = bfs();
	printf("%d\n", Result);
	Print(P(dx,dy));
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值