Description
給出一張地圖,這張地圖被分爲 n×m(n,m<=100)個方塊,任何一個方塊不是平地就是高山。平地可以通過,高山則不能。現在你處在地圖的(x1,y1)這塊平地,問:你至少需要拐幾個彎才能到達目的地(x2,y2)?你只能沿着水平和垂直方向的平地上行進,拐彎次數就等於行進方向的改變(從水平到垂直或從垂直到水平)的次數。例如:如圖 1,最少的拐彎次數爲5。
Input
第 1行:n m 第 2至n+1行:整個地圖地形描述(0:空地;1:高山), 如圖,第2行地形描述爲:1 0 0 0 0 1 0 第3行地形描述爲:0 0 1 0 1 0 0 …… 第n+2行:x1 y1 x2 y2 (分別爲起點、終點座標)
Output
s (即最少的拐彎次數
Sample Input
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
Sample Output
5
分析&說明:
這道題我的主體部分還是廣搜模板 。就是輸出函數那裏改了1點點地方·。以下爲輸出函數:
void print(int x)
{
if (father[x]==0) return;
else print(father[x]);
if(state[x][1]-state[father[x]][1]==0) f=2; else f=1;
if(father[father[x]]==0) b=f;
if(b!=f) s++,b=f;
}
s爲統計變量,b=s;f爲判斷當前的走法(平行或垂直),b爲判斷上一次的走法,方便看出是否有轉彎(垂直就是轉彎)。
後面就是模板
代碼:
#include<cstdio>
#include<iostream>
using namespace std;
int b,f,m,n,a[101][101],state[11000][3],s,father[11000],x,y,px,py,best;
short dx[5]={0,1,0,-1,0},dy[5]={0,0,1,0,-1};
char c;
bool check(int x,int y)
{
//判斷非法函數
if (1>x||x>n||1>y||y>m||a[x][y]==1) return false;
return true;
}
void print(int x)
{
if (father[x]==0) return;
else print(father[x]);
if(state[x][1]-state[father[x]][1]==0) f=2; else f=1;
if(father[father[x]]==0) b=f;
if(b!=f) s++,b=f;
//轉彎函數(輸出函數)
}
void bfs()
{
int tail,head;
state[1][1]=x;state[1][2]=y;state[1][3]=0;tail=1;head=0;
do
{
//廣搜主體
head++;
for (int i=1;i<=4;i++)
{
if(check(state[head][1]+dx[i],state[head][2]+dy[i]))
{
tail++;
father[tail]=head;
state[tail][1]=state[head][1]+dx[i];
state[tail][2]=state[head][2]+dy[i];
a[state[tail][1]][state[tail][2]]=1;
if (state[tail][1]==px&&state[tail][2]==py)
{
print(tail);
tail=0;
}
}
}
}
while (head<tail);
}
int main()
{
cin>>n>>m;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
cin>>a[i][j];
cin>>x>>y>>px>>py;
bfs();
cout<<s;
}