BFS求最短路径

求最短路径的时候一般用BFS,当然dfs也行

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int m, n;
int bx, by,ex,ey;
char map[30][30];
int vis[30][30];
int next_step[4][2] = {
    
     {
    
    1,0},{
    
    -1,0},{
    
    0,1},{
    
    0,-1 } };
struct  point {
    
    
	int x;
	int y;
	int setp;
};
queue<point> q;
void bfs() {
    
    
	vis[bx][by] = 1;
	point p;
	p.x = bx;
	p.y = by;
	p.setp = 0;
	q.push(p);
	while (!q.empty())
	{
    
    
		point temp;
		temp = q.front();
		q.pop();
		if (temp.x==ex&&temp.y==ey)
		{
    
    
			cout << temp.setp ;
			return;
		}
		for (int i = 0; i < 4; i++)
		{
    
    
			int nx = temp.x + next_step[i][0];
			int ny = temp.y + next_step[i][1];
			if (nx>=0&&ny>=0&&nx<m&&ny<n&&!vis[nx][ny]&&map[nx][ny]!='#')
			{
    
    
				point pt;
				pt.x = nx;
				pt.y = ny;
				pt.setp = temp.setp + 1;
				vis[nx][ny] = 1;
				q.push(pt);
			}
		}
	}
	cout << -1;
}
int main() {
    
    
	ios::sync_with_stdio(false); cin.tie(0);
	//memset(vis, 0, sizeof(vis));
	cin >> m >> n;
	for (int i = 0; i < m; i++)
		for (int j = 0; j < n; j++)
		{
    
    
			cin >> map[i][j];
			if (map[i][j]=='@')
			{
    
    
				bx = i, by = j;
			}
			if (map[i][j] == '*')
			{
    
    
				ex = i, ey = j;
			}

		}

	  bfs();
	return 0;

}


例题

猜你喜欢

转载自blog.csdn.net/qq_47154574/article/details/108064023