一、介绍
- 在 FIFO 数据结构中,将
首先处理添加到队列中的第一个元素
。如上图所示,队列是典型的 FIFO 数据结构。 - 插入(insert)操作也称作入队(enqueue),新元素始终被添加在
队列的末尾
。 - 删除(delete)操作也被称为出队(dequeue)。 你只能移除
第一个元素
。 - 入队是队尾指针给最后一个赋值,出队只是移动了队首的指针而已。
- 内存资源有限,使用循环队列。
二、队列实现
你的实现应该支持如下操作:
MyCircularQueue(k)
: 构造器,设置队列长度为 k 。Front
: 从队首获取元素。如果队列为空,返回 -1 。Rear
: 获取队尾元素。如果队列为空,返回 -1 。enQueue(value)
: 向循环队列插入一个元素。如果成功插入则返回真。deQueue()
: 从循环队列中删除一个元素。如果成功删除则返回真。isEmpty()
: 检查循环队列是否为空。isFull()
: 检查循环队列是否已满。
C++代码实现:
class MyCircularQueue {
private:
vector<int> data;
int header;
int tail;
int size;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
data.resize(k);
header = -1;
tail = -1;
size = k;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if(isEmpty()) {
header = 0;
tail = 0;
data[tail] = value;
return true;
}
if(isFull()) {
return false;
}
tail = (tail + 1) % size;
data[tail] = value;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if(isEmpty()){
return false;
}
if(header == tail){
header = -1;
tail = -1;
return true;
}
header = (header + 1) % size;
return true;
}
/** Get the front item from the queue. */
int Front() {
if(isEmpty()){
return -1;
}
return data[header];
}
/** Get the last item from the queue. */
int Rear() {
if(isEmpty()){
return -1;
}
return data[tail];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return header == -1;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return ((tail + 1) % size) == header;
}
};
三、广度优先搜索(BFS)
广度优先搜索(BFS)的一个常见应用是找出从根结点到目标结点的最短路径。
1. 结点的处理顺序
- round1,我们处理根结点A
- round2,我们处理根A结点旁边的结点BCD
- round3,我们处理距根结点两步的结点EFG
- 等等等等
与树的层序遍历类似,越是接近根结点的结点将越早地遍历
。
如果在第 k 轮中将结点 X
添加到队列中,则根结点与 X
之间的最短路径的长度恰好是 k
。也就是说,第一次找到目标结点时,你已经处于最短路径中。
2. 队列的入队和出队顺序
首先将根结点排入队列。
然后在每一轮中,我们逐个处理已经在队列中的结点,并将所有邻居(子节点)添加到队列中。值得注意的是,新添加的节点不会
立即遍历,而是在下一轮中处理。
结点的处理顺序与它们添加
到队列的顺序是完全相同的顺序
,即先进先出(FIFO)。这就是我们在 BFS 中使用队列的原因。
四、相关的Leetcode例子
Leetcode算法题:岛屿数量(BFS&DFS)
https://blog.csdn.net/yfy1127yfy/article/details/102955020
Leetcode算法题:打开转盘锁(BFS)