codeup22398_最少转弯问题

codeup22398_最少转弯问题

时空限制    1000ms/128MB

题目描述

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

输入

第1行:n   m
第2至n+1行:整个地图地形描述(0:空地;1:高山),
如(图1)第2行地形描述为:1 0 0 0 0 1 0
           第3行地形描述为:0 0 1 0 1 0 0
           ……
第n+2行:x1 y1 x2 y2 (分别为起点、终点坐标)

输出

s (即最少的拐弯次数)

样例输入

5 7
1 0 0 0 0 1 0
0 0 1 0 1 0 0
0 0 0 0 1 0 1
0 1 1 0 0 0 0
0 0 0 0 1 1 0
1 3 1 7

样例输出

5

 

代码

法一:STL队列

#include<iostream>
#include<queue>
using namespace std;
const int N = 105;
const int dx[] = {-1, 0, 1, 0},
		  dy[] = { 0, 1, 0,-1};
int n,m,x1,y1,x2,y2;
bool g[N][N];
struct node{
	int x,y,turn;
	node(){ }
	node(int a,int b,int c):x(a),y(b),turn(c){ }
};
queue<node> q;

int bfs(){
	q.push(node(x1,y1,0));
	g[x1][y1] = true;
	while (!q.empty()){
		node k=q.front(); q.pop();
		if (k.x==x2 && k.y==y2) return k.turn-1;	//到达终点 队头-1为答案
		for (int i=0; i<4; i++){	//四个方向
			int x=k.x+dx[i],y=k.y+dy[i];
			while (x>=1 && x<=n && y>=1 && y<=m && !g[x][y]){
				q.push(node(x,y,k.turn+1));
				g[x][y] = true;
				x+=dx[i]; y+=dy[i];		//沿着这个方向一直走下去
			}
		}
	}
}

int main(){
	cin>>n>>m;
	for (int i=1; i<=n; i++)
		for (int j=1; j<=m; j++) cin>>g[i][j];
	cin>>x1>>y1>>x2>>y2;
	if (x1==x2 && y1==y2) cout<<0<<endl;
	else cout<<bfs()<<endl;
	return 0;
}

法二:手动队列

#include<iostream>
using namespace std;
const int N = 105;
const int dx[] = {-1, 0, 1, 0},
		  dy[] = { 0, 1, 0,-1};
int n,m,x1,y1,x2,y2,que[N*N][3],head,tail;
bool g[N][N];

int bfs(){
	head=0; tail=0;
	que[++tail][1]=x1; que[tail][2]=y1; que[tail][0]=0;
	g[x1][y1] = true;
	while (head<tail){
		head++;
		if (que[head][1]==x2 && que[head][2]==y2) return que[head][0]-1;	//到达终点 队头-1为答案
		for (int i=0; i<4; i++){	//四个方向
			int x=que[head][1]+dx[i],y=que[head][2]+dy[i];
			while (x>=1 && x<=n && y>=1 && y<=m && !g[x][y]){
				que[++tail][1]=x; que[tail][2]=y; que[tail][0]=que[head][0]+1;
				g[x][y] = true;
				x+=dx[i]; y+=dy[i];		//沿着这个方向一直走下去
			}
		}
	}
}

int main(){
	cin>>n>>m;
	for (int i=1; i<=n; i++)
		for (int j=1; j<=m; j++) cin>>g[i][j];
	cin>>x1>>y1>>x2>>y2;
	if (x1==x2 && y1==y2) cout<<0<<endl;
	else cout<<bfs()<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值