数据结构OJ作业——队列
2017-03-28 12:40
260 查看
POJ 3984 :http://poj.org/problem?id=3984
迷宫,输出最短路径,bfs
POJ 3278:http://poj.org/problem?id=3278
bfs即可
迷宫,输出最短路径,bfs
#include <iostream> #include <cstdio> #include <queue> #include <cstring> using namespace std; int maze[5][5]; pair<int, int> path[5][5]; queue<pair<int,int> > q; int dx[]={1,-1,0,0}; int dy[]={0,0,1,-1}; void bfs(int x,int y) { q.push(make_pair(x,y)); while (!q.empty()) { pair<int, int> p = q.front(); q.pop() ; x = p.first; y = p.second; for (int i = 0; i < 4; i ++) { int xx = x + dx[i]; int yy = y + dy[i]; if (xx >= 0 && xx <= 4 && yy >= 0 && yy <= 4 && !maze[xx][yy]) { maze[xx][yy] = 1; path[xx][yy] = make_pair(x,y); if (xx == 0 && yy == 0) { return; } q.push(make_pair(xx,yy)); } } } } int main() { memset(path,-1,sizeof(path)); for (int i = 0; i < 5; i ++) { for (int j = 0; j < 5; j ++) { scanf("%d",&maze[i][j]); } } bfs(4,4); int x = 0, y = 0; while (x != 4 || y != 4) { printf("(%d, %d)\n",x,y); int xx = x; x = path[x][y].first; y = path[xx][y].second; } printf("(%d, %d)\n",4,4); return 0; }
POJ 3278:http://poj.org/problem?id=3278
bfs即可
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int MAX = 100005; int n,k; bool visit[MAX]; int step[MAX]; int mov[] = {1, -1}; int bfs(int x) { if (n >= k) { return n - k; } queue<int> q; q.push(x); visit[x] = 1; while (!q.empty()) { x = q.front(); q.pop(); //printf("%d ",x); for (int i = 0; i < 2; i ++) { int xx = x + mov[i]; if (xx == k) { return step[x] + 1; } if (xx >= 0 && xx <= 100000 && !visit[xx]) { q.push(xx); visit[xx] = 1; step[xx] = step[x] + 1; } } int xx = x * 2; if (xx == k) { return step[x] + 1; } if (xx <= 100000 && !visit[xx]) { q.push(xx); visit[xx] = 1; step[xx] = step[x] + 1; } } } int main() { while (~scanf("%d%d",&n,&k)) { memset(visit,0,sizeof(visit)); memset(step,0,sizeof(step)); printf("%d\n",bfs(n)); } }
相关文章推荐
- 数据结构作业——buzhidao(队列)
- 数据结构OJ作业 二叉树
- Huffman 编码 + 优先队列【算法+数据作业题】
- C++队列模拟银行排队叫号(加州大学伯克利分校计算机专业数据结构与算法作业)
- 数据结构OJ作业——栈
- 队列 数据结构作业(二)
- 截获网络数据包作业
- 第一次作业:网络数据截获
- Ethereal数据截获作业
- 往消息队列传数据的存储过程
- 队列::数据实现
- 第二次数据结构作业
- 数据队列的用处
- 数据截获作业
- 数据结构之队列(C语言)
- 学习引擎作业参考资源:数据挖掘技术
- 把Excel表中的数据导入数据库(存储过程、数据库作业)
- oracle job queue/oracle 作业队列
- 应用消息队列异步处理数据存储
- 第二次数据结构作业