您的位置:首页 > 理论基础 > 数据结构算法

数据结构OJ作业——队列

2017-03-28 12:40 260 查看
POJ 3984 :http://poj.org/problem?id=3984

迷宫,输出最短路径,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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 poj 队列