POJ 3984 迷宫初步 STL+BFS

这道题是简单的迷宫问题。刚进校队,数据结构很多地方不明白,这是我第一次尝试写BFS,顺便试着用栈保存查找路径。效率不高(保存路径比我方法好的多得是),不过应付这道题完全够了。

贴个代码,记录一下ACM路上的点滴。大牛见笑了~

 

 1 #include<iostream>
2 #include<queue>
3 #include<stack>
4 using namespace std;
5
6 typedef struct { int x; int y; int step; } Pos;
7 int maps[5][5], vis[5][5] = {0}, moveCol[4] = { 1, 0, -1, 0 }, moveRow[4] = { 0, 1, 0, -1 };
8 queue<Pos> qPos;
9 stack<pair<Pos, Pos>> path; //用栈记录遍历过的点
10 stack<pair<int, int>> final; //继续用栈保存待输出的点
11
12 void bfs(Pos start, Pos end)
13 {
14 while(!qPos.empty()) qPos.pop();
15 vis[start.x][start.y] = 1;
16 qPos.push(start);
17 while(!qPos.empty()) {
18 Pos now = qPos.front();
19 qPos.pop();
20 if(now.x == end.x && now.y == end.y) return;
21 for(int i = 0; i < 3; i++) {
22 Pos t = { now.x + moveRow[i], now.y + moveCol[i], now.step };
23 if(!vis[t.x][t.y] && !maps[t.x][t.y] && !(t.x < 0 || t.y < 0 || t.x >= 5 || t.y >= 5))
24 vis[t.x][t.y] = 1, t.step++, path.push(make_pair(now, t)), qPos.push(t);
25 }
26 }
27 }
28
29 int main()
30 {
31 int x = 4, y = 4; //初始化终点坐标
32 for(int i = 0; i < 5; ++i)
33 for(int j = 0; j < 5; ++j)
34 scanf("%d", &maps[i][j]);
35 Pos start = { 0, 0, 0 }, end = { 4, 4 };
36 bfs(start, end);
37 while(!path.empty()) {
38 if(path.top().second.x == x && path.top().second.y == y)
39 final.push(make_pair(x = path.top().first.x, y = path.top().first.y));
40 path.pop();
41 }
42 for(; !final.empty(); final.pop())
43 printf("(%d, %d)\n", final.top().first, final.top().second);
44 printf("(4, 4)\n");
45 return 0;
46 }

 

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