最小步数(广搜)

来源:互联网 发布:caffe可视化 编辑:程序博客网 时间:2024/06/05 11:16

最少步数

时间限制: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)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
23 1  5 73 1  6 7
样例输出
1211

#include<stdio.h>#include<string.h>#define MAXSIZE 81typedef  struct data{int row;int col;int step;}Data;typedef struct{int front, rear;Data q[9*9];}Queue;Data get_top(Queue *Q){Data a;a = Q->q[Q->front];return a;}int is_empty(Queue *Q){if(Q->rear == Q->front)return 1;return 0;}void init_queue(Queue *Q){int i;Q->front = Q->rear = 0;for(i = 0 ; i < MAXSIZE; i++)Q->q[i].step = 0;}void enqueue(Queue *Q, Data a){Q->q[Q->rear].row = a.row;Q->q[Q->rear].col = a.col;Q->q[Q->rear].step = a.step;Q->rear = (Q->rear +1)%MAXSIZE;}void dequeue(Queue * Q){Q->front = (Q->front +1)%MAXSIZE;}void min_step(Queue *Q, int row, int col);int a[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 Srow, Scol;int Erow, Ecol;int dir[4][4] = { {-1,0},{1, 0},{0,-1},{0, 1}};int f[9][9];int main(){int  n, i;Queue Q;Data p;scanf("%d",&n);for(i = 0; i < n; i++){memset(f, 0, sizeof(f));init_queue(&Q); scanf("%d %d",&Srow, &Scol);scanf("%d %d",&Erow, &Ecol);f[Srow][Scol] = 1;p.row = Srow;p.col = Scol;p.step = 1;enqueue(&Q,p);min_step(&Q, Srow, Scol);}return 0;}void min_step(Queue *Q, int row, int col){Data b, p;int i;while(!is_empty(Q)){for(i = 0; i < 4; i++)//四个方向判断{b = get_top(Q);p = b;if(p.row == Erow && p.col == Ecol){printf("%d\n", b.step -1);return ;}p.row += dir[i][0];p.col +=dir[i][1];p.step = b.step +1;//记录步数;if(a[p.row][p.col] == 0 && p.row > 0 && p.col > 0 && p.row < 9 && p.col < 9 && f[p.row][p.col] == 0 )//判断是否已经进队;{f[p.row][p.col]= 1;enqueue(Q, p);}if(i == 3)dequeue(Q);}}}

原创粉丝点击