您的位置:首页 > 其它

nyoj 58-最少步数

2013-08-04 23:45 211 查看
点击打开链接


最少步数

时间限制: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,1

0表示道路,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


水题一道,无脑广搜就过了吧,以前写的,没什么可说的,有点对不起这个难度,现在看用stl代码可以减少一半以上

#include<stdio.h>
int map[9][9] = {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 queue[100][3] , haxi[9][9];
int head , tail;
int i , start_x , start_y , end_x , end_y;
void bfs()
{
while(head != tail)
{
if(queue[head][0] > 0 && map[queue[head][0] - 1][queue[head][1]] == 0 && haxi[queue[head][0] - 1][queue[head][1]] == 0)
{
queue[tail][0] = queue[head][0] - 1;
queue[tail][1] = queue[head][1];
queue[tail][2] = queue[head][2] + 1;
haxi[queue[tail][0]][queue[tail][1]] = 1;
if(queue[tail][0] == end_x && queue[tail][1] == end_y)
{
printf("%d\n" , queue[tail][2]);
return ;
}
tail++;
}
if(queue[head][0] < 8 && map[queue[head][0] + 1][queue[head][1]] == 0 && haxi[queue[head][0] + 1][queue[head][1]] == 0)
{
queue[tail][0] = queue[head][0] + 1;
queue[tail][1] = queue[head][1];
queue[tail][2] = queue[head][2] + 1;
haxi[queue[tail][0]][queue[tail][1]] = 1;
if(queue[tail][0] == end_x && queue[tail][1] == end_y)
{
printf("%d\n" , queue[tail][2]);
return ;
}
tail++;
}
if(queue[head][1] > 0 && map[queue[head][0]][queue[head][1] - 1] == 0 && haxi[queue[head][0]][queue[head][1] - 1] == 0)
{
queue[tail][0] = queue[head][0];
queue[tail][1] = queue[head][1] - 1;
queue[tail][2] = queue[head][2] + 1;
haxi[queue[tail][0]][queue[tail][1]] = 1;
if(queue[tail][0] == end_x && queue[tail][1] == end_y)
{
printf("%d\n" , queue[tail][2]);
return ;
}
tail++;
}
if(queue[head][1] < 8 && map[queue[head][0]][queue[head][1] + 1] == 0  && haxi[queue[head][0]][queue[head][1] + 1] == 0)
{
queue[tail][0] = queue[head][0];
queue[tail][1] = queue[head][1] + 1;
queue[tail][2] = queue[head][2] + 1;
haxi[queue[tail][0]][queue[tail][1]] = 1;
if(queue[tail][0] == end_x && queue[tail][1] == end_y)
{
printf("%d\n" , queue[tail][2]);
return ;
}
tail++;
}
head++;
}

}

int find_way(int x , int y)
{

head = 0 ;
tail = 1;
queue[head][0] = start_x;
queue[head][1] = start_y;
haxi[queue[head][0]][queue[head][1]] = 1;
bfs();
if(head == tail)
return 0;
else return 1;
}
int main()
{

int x,y;

scanf("%d" , &i);
while(i--)
{
scanf("%d %d %d %d" , &start_x , &start_y , &end_x , &end_y);
for(x = 0 ; x < 9 ; x++)
for(y = 0 ; y < 9 ; y++)
haxi[x][y] = 0;
if(find_way(start_x , start_y) == 0)
printf("0\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: