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++;
}
posted @ 2020-04-02 15:56  vito_wang  阅读(155)  评论(0编辑  收藏  举报