最少步数

来源:互联网 发布:诲女知之乎的语气 编辑:程序博客网 时间:2024/05/22 17:27

这有一个迷宫,有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 <iostream>#include<queue>#include<cstring>const int dx[4] = {0, 0,-1, 1};const int dy[4] = {-1,1, 0, 0};struct node{    int x, y;    int step;};node now, next;node S,E;using namespace std;bool vis[10][10];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 bfs(){    if(S.x == E.x && S.y == E.y)        return 0;    memset(vis, false,sizeof(vis));    queue<node>q;    q.push(S);    vis[S.x][S.y] = true;    while(!q.empty())    {        now = q.front();        q.pop();        for(int i=0; i<4; i++)        {            next.x = now.x + dx[i];            next.y = now.y + dy[i];            next.step = now.step + 1;            if(map[next.x][next.y] == 1||next.x > 9 || next.x<0 || next.y>9 || next.y<0 || vis[next.x][next.y])                continue;            vis[next.x][next.y] = true;            q.push(next);            if(next.x == E.x && next.y == E.y)                return next.step;        }    }    return -1;}int main(){    int T;    int x1, y1, x2, y2;    cin >> T;    while(T--)    {        cin >> x1 >> y1;        cin >> x2 >> y2;        S.x = x1;        S.y = y1;        S.step = 0;        E.x = x2;        E.y = y2;        int ans = bfs();        if(ans >= 0)        cout << ans << endl;    }    return 0;}

0 0
原创粉丝点击