bfs广度遍历搜索模版
不需要记录层次
deque<datatype> deq;
deq.push_back(root);
while (!deq.empty())
{
auto cur = deq.front();
deq.pop_front();
for (auto x: cur的相邻节点)
{
if (!visited(x))
dep.push_back(x);
}
}
需要记录层次
deque<datatype> deq;
deq.push_back(root);
int level = 0;
while (!deq.empty())
{
int size = deq.size(); //当前队列中都是同一层的节点
while(size--)
{
auto cur = deq.front();
deq.pop_front();
for (auto x: cur的相邻节点)
{
if (!visited(x))
dep.push_back(x);
}
}
level++;
}