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;
}