麻将游戏(mahjong)
这道题本来和最小转弯问题是类似的,但因为我的上一篇最小转弯的博客分享了另一种非正解的解法,所以这道题只能重新想。
思路: 这道题和转弯问题的区别就在于:他可以走到棋盘外面。 所以我们把棋盘扩大再找最小转弯就行啦。套广搜的板子,代价是转弯次数,向一个方向走到底,如果没走过并且不是墙,存入队列,走过但是不是墙,继续走但不存入队列。细节还是很多的,挺考验代码能力。
AC代码:
#include<bits/stdc++.h>
using namespace std;
int a[80][80],b[80][80];
int n,m,x1,y3,x2,y2,h,t;
int fx[5]={0,1,0,-1,0},fy[5]={0,0,1,0,-1};
char x;
struct k
{
int x,y,s;
}s[6400];
bool check(int x,int y)
{
if (b[x][y]!=1&&x>0&&x<=n&&y>0&&y<=m)
return true;
else return false;
}
int main()
{
scanf("%d%d",&m,&n);
char x=getchar();//字符串输入
for (int i=1;i<=n;i++)
{
for (int j=1;j<=m;j++)
{
char x=getchar();
if (x=='X')
a[i+1][j+1]=1;
else a[i+1][j+1]=0;
}
char x=getchar();
}
n+=2; m+=2; //扩大地图
cin>>y3>>x1>>y2>>x2;
while (x1!=0)
{
x1++; y3++; x2++; y2++;//点坐标反过来在加一
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
b[i][j]=a[i][j]; //复制地图便于操作
b[x2][y2]=0;
s[1].x=x1; s[1].y=y3; s[1].s=0;
h=0; t=1;
int c=0;
do{//bfs模板
h++;
for (int i=1;i<=4;i++)
{
int j=1;
while (check(s[h].x+fx[i]*j,s[h].y+fy[i]*j))
{
if (b[s[h].x+fx[i]*j][s[h].y+fy[i]*j]!=2)
{
t++;
s[t].x=s[h].x+fx[i]*j;
s[t].y=s[h].y+fy[i]*j;
s[t].s=s[h].s+1;
b[s[t].x][s[t].y]=2;
if (s[t].x==x2&&s[t].y==y2)
{
cout<<s[t].s<<endl;
c=1;
break;
}
}
j++;
}
if (c==1)
break;
}
if (c==1)
break;
}while(h<t);
if (h==t)//h==t则无解输出0
cout<<0<<endl;
scanf("%d%d%d%d",&y3,&x1,&y2,&x2);
}
return 0;
}