题目分析: r行,c列的矩形,每个方格内有0-7七个数字,分别代表 north, south, east, west, northeast, northwest, southeast, southwest. 七个方向,一艘船 走向它的格子所表示的方向 不消耗能量,否则消耗一个能量,从起点到终点要消耗的最小能量,
分析:每个格子可以达到的而且不消耗能量的格子,同属一个集合,一次全把它们加到队列里,直到走到终点
注意:1.忘了清空队列
2.写代码时候要认真,老犯逻辑错误
3.C ++提示编译错误,G++ AC了
代码:
#include<iostream>
#include<cstdio>
#include<memory.h>
#include<queue>
using namespace std;
int r,c,n;
int maze[1100][1100],vis[1100][1100];
int dir[8][2]={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
struct node
{
int x,y;
int energy;
};
queue<node>q;
bool IN(int x,int y)
{
if(1<=x&&x<=r && 1<=y&&y<=c)
return true;
else
return false;
}
int main()
{
while(scanf("%d %d",&r,&c)!=EOF)
{
getchar();
for(int i=1;i<=r;i++)
{
for(int j=1;j<=c;j++)
{
char ch;
ch=getchar();
maze[i][j]=ch-'0';
}
getchar();
}
scanf("%d",&n);
node start,cur,temp,temp1;
int ans,flag;
for(int i=1;i<=n;i++)
{
int rs,cs,rd,cd;
scanf("%d %d %d %d",&rs,&cs,&rd,&cd);
if(rs==rd&&cs==cd)
{
printf("0\n");
continue;
}
/***忘了清空队列!!!!!*/
while(!q.empty())
q.pop();
memset(vis,0,sizeof(vis));
ans=0,flag=0;
start.x=rs,start.y=cs,start.energy=0;
temp1=start;
while(IN(temp1.x,temp1.y) && vis[temp1.x][temp1.y]==0)
{
if(temp1.x==rd && temp1.y==cd)
{
ans=0;
printf("0\n");
flag=1;
break;
}
int x1=temp1.x,y1=temp1.y;
q.push(temp1);
//printf("(%d %d---%d) ",x1,y1,temp1.energy);
vis[x1][y1]=1;
temp1.x=x1+dir[maze[x1][y1]][0];
temp1.y=y1+dir[maze[x1][y1]][1];
}
//printf("\n");
if(flag==1)
continue;
while(!q.empty())
{
temp=q.front();
//printf("(%d %d %d)\n",temp.x,temp.y,temp.energy);
q.pop();
/***cur.energy=temp.energy+1;*/
for(int i=0;i<8;i++)
{
cur.x=temp.x+dir[i][0];
cur.y=temp.y+dir[i][1];
if(i==maze[temp.x][temp.y])
cur.energy=temp.energy;
else
cur.energy=temp.energy+1;
temp1=cur;
while(IN(temp1.x,temp1.y)&&vis[temp1.x][temp1.y]==0)
{
if(temp1.x==rd && temp1.y==cd)
{
ans=temp1.energy;
flag=1;
break;
}
int x1=temp1.x,y1=temp1.y;
q.push(temp1);
//printf("(%d %d---%d) ",x1,y1,temp1.energy);
vis[x1][y1]=1;
temp1.x=x1+dir[maze[x1][y1]][0];
temp1.y=y1+dir[maze[x1][y1]][1];
temp1.energy=cur.energy;
}
if(flag==1)
break;
}
if(flag==1)
break;
}
printf("%d\n",ans);
}
}
return 0;
}