Letcode中C++队列的用法和广度优先搜索算法
1、队列的使用
#include <iostream>
int main() {
// 1. Initialize a queue.
queue<int> q;
// 2. Push new element.
q.push(5);
q.push(13);
q.push(8);
q.push(6);
// 3. Check if queue is empty.
if (q.empty()) {
cout << "Queue is empty!" << endl;
return 0;
}
// 4. Pop an element.
q.pop();
// 5. Get the first element.
cout << "The first element is: " << q.front() << endl;
// 6. Get the last element.
cout << "The last element is: " << q.back() << endl;
// 7. Get the size of the queue.
cout << "The size is: " << q.size() << endl;
}
2、广度优先搜索
(1)建立状态表,将所有状态置为未被发现状态
(2)创建队列,将初始位置放入队列中,对该位置做处理,将该位置状态变为发现状态
(3)将关联位置入队列,当队列不为空时,循环处理,优先处理先入队列的元素