POJ 1101 连连看找最短线段

题意,给你一张地图,图上空格表示连接的线段可以穿过,X表示方块而且线段不能穿过。下面给出一些待连接的方块坐标,求连线的最短线段数。

我的思路是BFS,声明一个结构体保存当前的点坐标、方向和已走线段数,遇到拐弯(方向变化)就更新已走过的线段数。

最初用优先队列写的,Wrong Answer到郁闷,最后单步调试发现当线段数相同时,会产生哪个点先下一步的优先级问题。最后还是用队列解决问题。

这道题难点应该没有,就是输入地图时要注意下,每行有回车,输完一行记得getchar()一下。然后就是,输入给出的点坐标,第一个是纵坐标,第二个是横坐标,坐我后面的同学因为这个WA了半天,哈哈。

 

  1 #include<iostream>
2 #include<queue>
3 using namespace std;
4
5 typedef struct
6 {
7 int x;
8 int y;
9 int direction;
10 int seg;
11 } Pos;
12 char maps[100][100] = {0};
13 bool vis[100][100] = {0};
14 int dir[4][2] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
15 queue<Pos> qPos;
16
17 bool isOverflow(const Pos cur, int w, int h)
18 {
19 if(cur.x < 0 || cur.y < 0 || cur.x > h + 1 || cur.y > w + 1)
20 return true;
21 return false;
22 }
23
24 int bfs(Pos start, Pos end, int w, int h)
25 {
26 int minimum = 0;
27 while(!qPos.empty())
28 qPos.pop();
29 memset(vis, 0, sizeof(vis));
30 vis[start.x][start.y] = true;
31 qPos.push(start);
32 while(!qPos.empty())
33 {
34 Pos now = qPos.front();
35 qPos.pop();
36 for(int i = 0; i < 4; i++)
37 {
38 Pos t = { now.x + dir[i][0], now.y + dir[i][1], now.direction, now.seg };
39 if(t.x == end.x && t.y == end.y)
40 {
41 if(t.direction != i)
42 {
43 t.seg++;
44 t.direction = i;
45 }
46 if(t.seg != 0)
47 {
48 if(t.seg < minimum || minimum == 0)
49 {
50 minimum = t.seg;
51 }
52 }
53 vis[t.x][t.y] = true;
54 continue;
55 }
56 if(!vis[t.x][t.y] && maps[t.x][t.y] != 'X' && !isOverflow(t, w, h))
57 {
58 if(t.direction != i)
59 {
60 t.seg++;
61 t.direction = i;
62 }
63 qPos.push(t);
64 vis[t.x][t.y] = true;
65 }
66 }
67 }
68 return minimum;
69 }
70
71 int main()
72 {
73 int w, h, t = 1;
74 while(scanf("%d%d",&w,&h)!=EOF)
75 {
76 getchar();
77 if(w == 0 && h == 0) break;
78 printf("Board #%d:\n", t++);
79 memset(maps,0,sizeof(maps));
80 for(int i=1; i<=h; i++)
81 {
82 for(int j=1; j<=w; j++)
83 {
84 scanf("%c", &maps[i][j]);
85 }
86 getchar();
87 }
88 for(int order = 1;; order++)
89 {
90 Pos start, end;
91 int steps;
92 scanf("%d%d%d%d", &start.y, &start.x, &end.y, &end.x);
93 if(start.y == 0 && start.x == 0&& end.y == 0 && end.x == 0) break;
94 printf("Pair %d: ", order);
95 start.direction = -1;
96 start.seg = 0;
97 steps = bfs(start, end, w, h);
98 if(steps == 0)
99 {
100 printf("impossible.\n");
101 }
102 else
103 {
104 printf("%d segments.\n", steps);
105 }
106 }
107 printf("\n");
108 }
109 return 0;
110 }

 

posted @ 2012-02-11 21:11  dgsrz  阅读(304)  评论(0编辑  收藏  举报