没有权值考虑的广搜,不过大神用的神搜代码很简洁:

 

 
#include<cstdio>
#define min(x,y) x>y?y:x
int maze[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 a,b,c,d,m;
void dfs(int x,int y,int s){
    if(maze[x][y]) return;
    if(x==c&&y==d){
        m=min(s,m);
        return;
    }
    s++;
    maze[x][y]=1;
    dfs(x+1,y,s);
    dfs(x,y+1,s);
    dfs(x-1,y,s);
    dfs(x,y-1,s);
    maze[x][y]=0;
}

int main(){
    int n;
    scanf("%d",&n);
    while(n--){
        m=9999;
        scanf("%d%d%d%d",&a,&b,&c,&d);
        dfs(a,b,0);
        printf("%d\n",m);
    }
    return 0;
}       

 

 

我的广搜:

 

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

struct q
{
    int row;
    int col;
    int step;
};
int a,b,c,d;
int head = 1,tail =2;
q que[100];
int s1[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(int a, int b, int c, int d)
{
    int s[9][9];
    memcpy(s,s1,sizeof(s1));
    head = 1,tail =2;
    que[head].row = a;
    que[head].col = b;
    que[head].step = 0;
    while(head < tail)
   {
       if(que[head].row == c && que[head].col == d )
       {
         return que[head].step;
       }
       int m = que[head].row;
       int n = que[head].col;
       if(s[m][n+1] == 0)
       {
           s[m][n+1] = 1;
           que[tail].row = m,que[tail].col  = n+1,que[tail].step = que[head].step +1;
           tail ++;
       }
        if(s[m+1][n] == 0)
       {

           s[m+1][n] = 1;
           que[tail].row = m+1,que[tail].col = n,que[tail].step = que[head].step +1;
            tail ++;
       }
        if(s[m][n-1] == 0)
       {
           s[m][n-1] = 1;
           que[tail].row = m,que[tail].col = n-1,que[tail].step = que[head].step +1;
            tail ++;
       }
        if(s[m-1][n] == 0)
       {

           s[m-1][n] =1;
           que[tail].row = m-1,que[tail].col = n,que[tail].step = que[head].step +1;
            tail ++;
       }
       head ++;
   }
}
int main()
{
    int n;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d%d%d%d",&a,&b,&c,&d);
      cout << bfs(a,b,c,d) << endl;
    }
    return 0;
}