1. 程式人生 > >南陽理工OJ_題目58 最少步數

南陽理工OJ_題目58 最少步數

#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

int bfs();

struct data
{
    int x;
    int y;
    int d;
    int vis;
};

char ch[11][11] = {  "111111111",
                    "100100101",
                    "100110001",
                    "101011011",
                    "100001001",
                    "110101001",
                    "110101001",
                    "110100001",
                    "111111111",
                    };
data a[11][11];
int x1;
int y1;
int x2;
int y2;

int main()
{
    int T;
    cin >> T;
    while(T--)
    {
        cin >> x1 >> y1 >> x2 >> y2;
        cout << bfs() << '\n';
    }
}

int bfs()
{
    data t;
    queue<data> q;
    memset(a, 0, sizeof(a));
    a[x1][y1].vis = 1;
    a[x1][y1].x = x1;
    a[x1][y1].y = y1;
    a[x1][y1].d = 0;
    q.push(a[x1][y1]);
    while(!q.empty())
    {
        t = q.front();
        q.pop();
        if(t.x == x2 && t.y == y2)
            return t.d;
        if(ch[t.x+1][t.y] == '0' && a[t.x+1][t.y].vis == 0)
        {
            a[t.x+1][t.y].vis = 1;
            a[t.x+1][t.y].d = t.d+1;
            a[t.x+1][t.y].x = t.x+1;
            a[t.x+1][t.y].y = t.y;
            q.push(a[t.x+1][t.y]);
        }
        if(ch[t.x-1][t.y] == '0' && a[t.x-1][t.y].vis == 0)
        {
            a[t.x-1][t.y].vis = 1;
            a[t.x-1][t.y].d = t.d+1;
            a[t.x-1][t.y].x = t.x-1;
            a[t.x-1][t.y].y = t.y;
            q.push(a[t.x-1][t.y]);
        }
        if(ch[t.x][t.y+1] == '0' && a[t.x][t.y+1].vis == 0)
        {
            a[t.x][t.y+1].vis = 1;
            a[t.x][t.y+1].d = t.d+1;
            a[t.x][t.y+1].x = t.x;
            a[t.x][t.y+1].y = t.y+1;
            q.push(a[t.x][t.y+1]);
        }
        if(ch[t.x][t.y-1] == '0' && a[t.x][t.y-1].vis == 0)
        {
            a[t.x][t.y-1].vis = 1;
            a[t.x][t.y-1].d = t.d+1;
            a[t.x][t.y-1].x = t.x;
            a[t.x][t.y-1].y = t.y-1;
            q.push(a[t.x][t.y-1]);
        }
    }
}