bfs经典例题

  1. 给定一个大小为N x M的迷宫。迷宫由通道和墙壁组成,每一步可以由邻接的上下左右四格的通道移动。请求出从起点到终点所需最小步数。
    (’#’、’.’、‘S’、'G’分别表示墙壁、通道、起点、终点)
    输入:
10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#

输出:

22
#include <iostream>
#include <queue>
using namespace std;
int n, m;
int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
char s[105][105];
int dis[105][105];
struct node{
	int x, y;
	node(int _x, int _y)
	{
		x = _x;
		y = _y;
	}
};

int bfs(int x, int y)
{
	queue<node> q;
	q.push(node(x, y));
	dis[x][y] = 0;
	while (!q.empty())
	{
		node now = q.front();
		q.pop();
		if (s[now.x][now.y] == 'G')
		{
			return dis[now.x][now.y];
		}
		for (int i = 0; i < 4; i++)
		{
			int tx = now.x + dir[i][0], ty = now.y + dir[i][1];
			if (tx < 0 || tx >= n || ty < 0 || ty >= m || s[tx][ty] == '#' || dis[tx][ty] != 0x3f3f3f3f)
			{
				continue;
			}
			dis[tx][ty] = dis[now.x][now.y] + 1;
			q.push(node(tx, ty));
		}
	}
}
int main()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++)
	{
		scanf("%s", s[i]);
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			dis[i][j] = 0x3f3f3f3f;
		} 
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (s[i][j] == 'S')
			{
				cout << bfs(i, j) << endl;
				break;
			}
		}
	}
	return 0;
}
  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值