侧边栏壁纸
  • 累计撰写 192 篇文章
  • 累计创建 2 个标签
  • 累计收到 87 条评论

【题解】走出迷宫的最少步数

Allen Best
2023-07-10 / 0 评论 / 0 点赞 / 9 阅读 / 818 字
温馨提示:
本文最后更新于 2023-07-10,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
#include<bits/stdc++.h>
using namespace std;
char a[41][41];
int n,m,vis[41][41],ans;
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
bool check(int x,int y)
{
	if(x>=1&&x<=n&&y>=1&&y<=m&&!vis[x][y]&&a[x][y]=='.')return true;
	return false;
}
struct pace{
	int x,y,step;
};
queue<pace>q;
void bfs(int x,int y)
{
	pace now;
	now.x=x;
	now.y=y;
	now.step=1;
	q.push(now);
	while(q.size())
	{
		pace cur=q.front();
		q.pop();
		if(cur.x==n&&cur.y==m)
		{
			ans=cur.step;
			return;
		}
		for(int i=0;i<4;i++)
		{
			int nx=cur.x+dir[i][0];
			int ny=cur.y+dir[i][1];
			if(check(nx,ny))
			{
				vis[nx][ny]=1;
				pace next;
				next.x=nx;
				next.y=ny;
				next.step=cur.step+1;
				q.push(next);
			}
		}
	}
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)cin>>a[i][j];
	}
	memset(vis,0,sizeof(vis));
	vis[1][1]=1;
	bfs(1,1);
	cout<<ans<<endl;
}
0

评论区