描述

这有一个迷宫,有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)。)

<dl class="others"> <dt> 输入 </dt> <dd> 第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。 </dd> <dt> 输出 </dt> <dd> 输出最少走几步。 </dd> <dt> 样例输入 </dt> <dd>
2
3 1  5 7
3 1  6 7
</dd> <dt> 样例输出 </dt> <dd>
12
11
</dd> </dl>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int m[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 n[10][10];
int s[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int x,y,x1,y1,w;
void dfs(int a,int b,int c)
{
    int d,e,f;
    if(a==x1&&b==y1)
    {
        if(c<w)           //判断当前步数是否比保存步数小
            w=c;
        return ;
    }
    for(d=0;d<4;d++)
    {
        e=a+s[d][0];
        f=b+s[d][1];
        if(m[e][f]==0&&e>=0&&e<9&&f>=0&&f<9&&n[e][f]==0)       //判断是否满足为0,并且未走过的条件
        {
            n[e][f]=1;       //标记走过的位置
            dfs(e,f,c+1);
            n[e][f]=0;
        }
    }
    return ;
}
int main()
{
    int a,b,c,d,e;
    cin>>a;
    while(a--)
    {
        memset(n,0,sizeof(n));
        cin>>x>>y>>x1>>y1;
        w=1000000;
        n[x][y]=1;
        dfs(x,y,0);
        cout<<w<<endl;
    }
    return 0;
}