【广搜】从起点S到达终点T的最少步数

一、问题描述 

给定一个n*m大小的迷宫,其中*代表不可通过的墙壁,而“.”代表平地,S表示起点,T代表终点。移动过程中,如果当前位置是(x,y)(下标从0开始),且每次只能前往上下左右(x,y+1)、(x,y-1)、(x-1,y)、(x+1,y)四个位置的平地,求从起点S到达终点T的最少步数。

` ` ` ` `

` * ` * `

` * S * `

` * * * `

` ` ` T *

在上面的样例中,S的坐标为(2,2),T的坐标为(4,3)。

二、代码实现

#include<iostream> 
#include<cstdio> 
#include<cstring>
#include<queue>
using namespace std;

const int maxn=100;

struct Node
{
	int x,y;
	int step;
}S,T,node;

int n,m; //n行,m列 
char maze[maxn][maxn];

bool inq[maxn][maxn]={false};

int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};

bool test (int x,int y)
{
	if(x>=n||x<0||y>=m||y<0) return false;
	if(maze[x][y]=='*') return false;
	if(inq[x][y]==true) return false;
	return true;
}

int BFS()
{
	queue<Node> q;
	q.push(S);
	while(!q.empty())
	{
		Node top=q.front();
		q.pop();
		if(top.x==T.x&&top.y==T.y)
		{
			return top.step;
		}
		for(int i=0;i<4;i++)
		{
			int newX=top.x+X[i];
			int newY=top.y+Y[i];
			if(test(newX,newY))
			{
				node.x=newX;
				node.y=newY;
				node.step=top.step+1;
				q.push(node);
				inq[newX][newY]=true;
			}
		}		
	}
	return -1;
}


int main() 
{
	scanf("%d%d",&n,&m);
	for(int i=0;i<n;i++)
	{
		getchar(); //吃掉换行符 
		for(int j=0;j<m;j++)
		{
			maze[i][j]=getchar();
		}
		//getchar();
		maze[i][m]='\0';
	}
	scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y);
	S.step=0; 
	printf("%d\n",BFS());
	return 0;
}

发布了180 篇原创文章 · 获赞 64 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/OpenStack_/article/details/104030526