最小步数 n 58 bfs

今晚的效率不高,,,,bfs还要再学学啊可怜可怜

#include<stdio.h>
#include<string.h>

int flag[9][9];
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 dir[4][2]={0,1,1,0,0,-1,-1,0};
int q[100][3];
int front=0,rear=0;
int step=0;

void bfs(int x, int y, int m, int n)
{
     q[rear][0] = x;
     q[rear][1] = y;
     q[rear][2] = step;
     rear++;
     flag[x][y] = 1;        //标记已走过(存入队列) 
     while(front < rear)
     {
          if(q[front][0]==m  &&  q[front][1]==n)
          {printf("%d\n", q[front][2]); break;}
          else
          {
              int i;
              for(i=0;i<4;i++)
              {
                     int tx = q[front][0] + dir[i][0];
                     int ty = q[front][1] + dir[i][1];
                     if(tx>=0 && tx<=8 && ty>=0 && ty<=8)
                     {
                              if(map[tx][ty]!=1 && flag[tx][ty]!=1)
                              {
                                   flag[tx][ty] = 1;
                                   q[rear][0] = tx;
                                   q[rear][1] = ty;
                                   q[rear][2] = q[front][2]+1;
                                   rear++;
                                   flag[tx][ty] = 1;
                              }
                     }
              }
              front++;
          }
     }
     
     
}

int main()
{
    int n, a, b, c, d;
    scanf("%d", &n);
    while(n--)
    {
              memset(flag, 0, sizeof(flag));
              memset(q, 0, sizeof(q));
              step = front = rear = 0;
              scanf("%d%d%d%d", &a, &b, &c, &d);
              bfs(a, b, c, d);            
    }
    return 0;
}


 

posted on 2011-12-08 01:23  java课程设计例子  阅读(164)  评论(0编辑  收藏  举报