最少步数

来源:互联网 发布:linux chmod怎么 编辑:程序博客网 时间:2024/04/28 14:19
描述

这有一个迷宫,有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
样例输出
12

11

//关键字:简单广搜

//标程:

#include<iostream>#include<cstdio>#include<cstring>#include<queue>using namespace std;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 dir[][2] = {1,0, 0,1, -1,0, 0,-1};int  x2,  y2, vis[10][10], flag;bool judge(int x,int y){if(x >= 0 && x <= 8 && y >= 0 && y <= 8 && !a[x][y] && !vis[x][y])return true;return false;}struct ss{int x, y, step;};queue<ss> q;void bfs(){while(!q.empty()){ss tmp = q.front();q.pop();if(tmp.x == x2 && tmp.y == y2){cout << tmp.step << endl;break;}for(int i = 0; i < 4; ++ i){ss new_tmp;new_tmp.x = tmp.x + dir[i][0];new_tmp.y = tmp.y + dir[i][1];new_tmp.step = tmp.step + 1;if(judge(new_tmp.x,new_tmp.y)){vis[new_tmp.x][new_tmp.y] = 1;q.push(new_tmp);}}}}int main(){// freopen("a.txt","r",stdin);    int t, i;    cin >> t;while(t --){int x1, y1;cin >> x1 >> y1 >> x2 >> y2;memset(vis,0,sizeof(vis));        ss tmp;tmp.x = x1, tmp.y = y1, tmp.step = 0;while(!q.empty()) q.pop();q.push(tmp);bfs();}return 0;}

0 0