洛谷P1649 【[USACO07OCT]障碍路线Obstacle Course】

题目描述

Consider an N x N (1 <= N <= 100) square field composed of 1

by 1 tiles. Some of these tiles are impassible by cows and are marked with an 'x' in this 5 by 5 field that is challenging to navigate:

. . B x .
. x x A .
. . . x .
. x . . .
. . x . .

Bessie finds herself in one such field at location A and wants to move to location B in order to lick the salt block there. Slow, lumbering creatures like cows do not like to turn and, of course, may only move parallel to the edges of the square field. For a given field, determine the minimum number of ninety degree turns in any path from A to B. The path may begin and end with Bessie facing in any direction. Bessie knows she can get to the salt lick.

N*N(1<=N<=100)方格中,’x’表示不能行走的格子,’.’表示可以行走的格子。卡门很胖,故而不好转弯。现在要从A点走到B点,请问最少要转90度弯几次?

输入格式

第一行一个整数N,下面N行,每行N个字符,只出现字符:’.’,’x’,’A’,’B’,表示上面所说的矩阵格子,每个字符后有一个空格。

【数据规模】

2<=N<=100

输出格式

一个整数:最少转弯次数。如果不能到达,输出-1。

题目分析:普通bfs在跑图时搜点记录的是最短路径(扩展层数),本题要求输出最小转弯次数,我们可以模仿dijkstra+堆优化将转弯数保存在小根堆中然后跑dijkstra, 由于堆顶始终最小,所以在bfs跑到时就能得出我们的答案

#include <bits/stdc++.h>
using namespace std;
char a[][];
int book[][];
int flag=;
int nx[]= {,,-,};
int ny[]= {,-,,};
int s1,s2;
int e1,e2;
struct node
{
int px=;
int py=;
int x=;
int y=;
int w=;
friend bool operator < (node a,node b)//小根堆
{
return a.w>b.w;
}
};
int w;
priority_queue<node> q;
int m,n;
void bfs()//dijkstra
{
node fir;
fir.x=s1;
fir.y=s2;
q.push(fir);
book[s1][s2]=;
while(!q.empty())
{
node now=q.top();
q.pop();
book[now.x][now.y]=;
if(now.x==e1&&now.y==e2)
{
//if(now.w<=flag)
{
flag=now.w;
break;
//return;
}
}
for(int i=; i<; i++)
{
int tx=now.x+nx[i];
int ty=now.y+ny[i];
if(tx<||tx>m||ty<||ty>m)
continue;
if(a[tx][ty]=='x')
continue;
if(book[tx][ty]==)
continue;
if((tx-now.x)*(now.x-now.px)+(ty-now.y)*(now.y-now.py)==)//向量判别法
{
node next;
next.x=tx;
next.y=ty;
next.px=now.x;
next.py=now.y;
next.w=now.w+;
q.push(next); }
else
{
node next;
next.x=tx;
next.y=ty;
next.px=now.x;
next.py=now.y;
next.w=now.w;
q.push(next); }
}
}
}
int main()
{
cin>>m;
memset(a,-,sizeof(a));
int x,y;
int z;
for(int i=; i<=m; i++)
for(int j=; j<=m; j++)
{
char c;
cin>>c;
if(c=='A')
{
s1=i;
s2=j;
}
if(c=='B')
{
e1=i;
e2=j;
}
a[i][j]=c;
}
bfs();
if(flag==)
cout<<-;
else
cout<<flag;
return ;
}
上一篇:[USACO07OCT]障碍路线Obstacle Course


下一篇:[洛谷1649]障碍路线