扩大
缩小

NYOJ58最少步数

最少步数

时间限制:3000 ms  |  内存限制:65535 KB
难度:4
 
描述

这有一个迷宫,有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)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
2
3 1  5 7
3 1  6 7
样例输出
12
11
View Code
 1  
 2 #include<iostream>
 3 #include<queue>
 4 using namespace std;
 5 typedef struct point 
 6 {
 7        int x,y,step;
 8 }point;
 9 int dir[4][2]={-1,0,0,1,0,-1,1,0};
10 
11 int bfs(point a,point b,int map[9][9])
12 {
13   queue<point> q;
14   q.push(a);
15   point temp;
16   while(1)
17   {
18       if(a.x==b.x&&a.y==b.y)return a.step;
19       for(int i=0;i<4;i++)
20       {
21         temp.x=a.x+dir[i][0];
22         temp.y=a.y+dir[i][1];
23         if(map[temp.x][temp.y]==0)
24         {
25           temp.step=a.step+1;
26           map[temp.x][temp.y]=1;
27          q.push(temp);
28         }
29       }
30       a=q.front();
31       q.pop();
32   }
33 }
34  
35 int main()
36 {
37     int ncase;
38     cin>>ncase;
39     while(ncase--)
40     {
41                   int map[9][9]={1,1,1,1,1,1,1,1,1,
42                         1,0,0,1,0,0,1,0,1,
43                         1,0,0,1,1,0,0,0,1,
44                         1,0,1,0,1,1,0,1,1,
45                         1,0,0,0,0,1,0,0,1,
46                         1,1,0,1,0,1,0,0,1,
47                         1,1,0,1,0,1,0,0,1,
48                         1,1,0,1,0,0,0,0,1,
49                         1,1,1,1,1,1,1,1,1,};
50        point s,e;
51        cin>>s.x>>s.y>>e.x>>e.y;
52        s.step=0;
53        map[s.x][s.y]=1;
54        cout<<bfs(s,e,map)<<endl;
55     }
56     return 0;
57 }
58        
59         

 

posted on 2012-11-14 21:50  LinuxPanda  阅读(496)  评论(0编辑  收藏  举报

导航