思路:用广搜搜索就是最短路径了;
最少步数
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,10表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
-
输入
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
- 输出最少走几步。 样例输入
-
2 3 1 5 7 3 1 6 7
样例输出
-
12 11
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define QUEUELEN 1000
//数据结构的定义
typedef struct
{
int x;
int y;
int pre;
}DATA;
typedef struct
{
DATA data[QUEUELEN];
int head;
int tail;
}SQType;
//队列的初始化
SQType *SQTypeInit()
{
SQType *q;
if(q=(SQType *)malloc(sizeof(SQType)))
{
q->head=0;
q->tail=0;
return q;
}
else
{
return NULL;
}
}
//判断空队列
int SQTypeIsEmpty(SQType *q)
{
int temp;
temp=q->head==q->tail;
return temp;
}
//判断满队列
int SQTypeisFull(SQType *q)
{
int temp;
temp=q->tail==QUEUELEN;
return temp;
}
//清空队列
void SQTypeClear(SQType *q)
{
q->head=0;
q->tail=0;
}
//释放空间
void SQTypeFree(SQType *q)
{
if (q!=NULL)
{
free(q);
}
}
//入队
int InSQType(SQType *q,DATA data)
{
if (q->tail==QUEUELEN)
{
printf("队列满鸟。。。");
return 0;
}
else
{
q->data[q->tail++]=data;
return 1;
}
}
//出队列
int OutSQType(SQType *q,DATA &a)
{
if(q->head==q->tail)
{
printf("亲,队列是空的。。。");
return 0;
}
else
{ a= q->data[q->head++];
return 1;
}
}
//读取节点的数据
DATA *PeekSQType(SQType *q)
{
if(SQTypeIsEmpty(q))
{
printf("\n这个队列是空的啊。。。\n");
return NULL;
}
else
{
return &(q->data[q->head]);
}
}
//计算队列的长度
int SQTypeLen(SQType *q)
{
int temp;
temp=q->tail-q->head;
return temp;
}
DATA h[100];
int bfs(int x,int y,int zx,int zy)
{ if(x==zx&&y==zy) {
printf("0\n");return 1; }
int mg[9][9]= //定义迷宫,0表示能走的块,1表示不能走,在外围加上一圈不能走的块
{
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1},
};
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int flag[9][9]={0};
SQType *migong=SQTypeInit();
DATA a={x,y,0};
int front=-1;
flag[1][1]=1;
InSQType(migong,a);
while(!SQTypeIsEmpty(migong))
{
OutSQType(migong,a);
for(int i=0;i<4;i++)
{
int nx=a.x+dir[i][0];
int ny=a.y+dir[i][1];
if(nx==zx&&ny==zy)
{
printf("%d\n",a.pre+1);return 1;
}
if(mg[nx][ny]==0&&!flag[nx][ny]&&nx>=0&&nx<=8&&ny>=0&&ny<=8)
{
DATA n;
n.pre=a.pre+1;
n.x=nx;
n.y=ny;
flag[nx][ny]=1;
InSQType(migong,n);
}
}
}
}
int main()
{ int n,x,y,zx,zy;
scanf("%d",&n);
while(n--)
{
scanf("%d%d%d%d",&x,&y,&zx,&zy);
bfs(x,y,zx,zy);
}
}