bfs最小转弯路径

2018/08/27 Offer 共 1205 字,约 4 分钟

题目描述

给出一张地图,这张地图被分为 n×m(n,m<=100)个方块,任何一个方块不是平地就是高山。平地可以通过,高山则不能。现在你处在地图的(x1,y1)这块平地,问:你至少需要拐几个弯才能到达目的地(x2,y2)?你只能沿着水平和垂直方向的平地上行进,拐弯次数就等于行进方向的改变(从水平到垂直或从垂直到水平)的次数。例如:如图 1,最少的拐弯次数为5。

保存每个节点的转弯次数

bfs遍历,当达到最终节点时,输出turn数量即可。此时就是最小转弯次数

所以要有个标记重复访问

while(!empty)里,for 4个方向,延伸,每次都到尽头

遇到没用过的就加入

代码

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
struct point{
	int x,y,turn;
}_begin,_end,p;
queue<point> q;
int n,m,_map[101][101];
bool used[101][101];
int main(){
	memset(used,0,sizeof(used));
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			scanf("%d",&_map[i][j]);
	scanf("%d %d %d %d",&_begin.x,&_begin.y,&_end.x,&_end.y);
	q.push(_begin);
	q.front().turn=0;
	while(!q.empty()){
		for(int i=0;i<4;i++){
			p.x=q.front().x+dx[i];
			p.y=q.front().y+dy[i];
			while(p.x>0&&p.x<=n&&p.y>0&&p.y<=m&&!_map[p.x][p.y]){
				if(!used[p.x][p.y]){
					if(p.x==_end.x&&p.y==_end.y){
						printf("%d\n",q.front().turn);
						return 0;
					}
					used[p.x][p.y]=1;
					p.turn=q.front().turn+1;
					q.push(p);
				}
				p.x+=dx[i];
				p.y+=dy[i];
			}
		}
		q.pop();
	}
}

Search

    Table of Contents