queue 队列数据结构
只支持从队前端弹出元素pop,队尾端插入数据push.不支持下标索引访问。
类函数比较少
push() pop() size() front() empty()
但是他是BFS 广度优先搜索的基础。
这里以poj 1915 为例子,演示在BFS中如何使用queue
poj 1915
https://vjudge.net/problem/POJ-1915
题目大意
输入一个正方形国际棋盘大小,和棋子所在坐标,以及要求走到的终点坐标。要求我们输出移动的最小次数。
棋子移动类似象棋的马,走日字格子,如图
输入
第一行 输入一个数字N 表示测试用例个数
每个用例包括三行
1 包括棋盘长度 4<=L<=300
2 棋子的起始位置 x y
3 棋子的目标位置 m n
输出
输出一行一个数字 表示移动的最少次数
Sample Input
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
Sample Output
5
28
0
解答
使用bfs逐步计算棋子可以走到的坐标,找到终点。
#include <iostream>
#include <queue>
using namespace std;
const int N = 310;
int board[N][N];
//每次移动的xy的增加量
int addx[8] = { 2,2,1,1,-1,-1,-2,-2 };
int addy[8] = { 1,-1,2,-2,2,-2,1,-1 };
//记录已经被访问了 避免重复访问
int vis[N][N];
int n;
struct INFO {
int x;
int y;
int step;
};
int main()
{
cin >> n;
while (n--) {
memset(vis, 0, sizeof vis);
int width;
int startx, starty;
int targetx, targety;
cin >> width;
cin >> startx >> starty;
cin >> targetx >> targety;
if (startx == targetx && starty == targety) {
cout << 0 << endl;
continue;
}
queue<struct INFO> q;
//队列中存储的信息有三个元素 走到的坐标x 做到的坐标y 使用到的步数
struct INFO info; info.x = startx; info.y = starty; info.step = 0;
q.push(info);
vis[startx][starty] = 1;
while (!q.empty()) {
int currx = q.front().x;
int curry = q.front().y;
int currstep = q.front().step;
q.pop();
if (currx == targetx && curry == targety) {
//达到终点
cout << currstep << endl;
break;
}
//尝试向八个方向移动
for (int i = 0; i < 8; i++) {
int newx = currx + addx[i];
int newy = curry + addy[i];
//检测新得到的坐标是否合法 是否已经被访问过
if (newx >= 0 && newx < width && newy >= 0 && newy < width && vis[newx][newy] == 0) {
struct INFO info; info.x = newx; info.y = newy; info.step = currstep +1;
q.push(info); vis[newx][newy] = 1;
}
}
}
}
}