赞
踩
下面是实现的代码,需要借助队列来完成:
- // 图的广度优先遍历
- void BFS(const V& v)
- {
- queue<int> q;
- //标记是否已经遍历,遍历过为true
- vector<bool> visited(_v.size(), false);
- size_t index = GetIndexOfV(v);
- q.push(index);
- _BFS(q, visited);
-
- //避免漏掉与其他顶点无关的点
- for (size_t i = 0; i < _v.size(); i++)
- {
- if (visited[i] == false)
- {
- q.push(i);
- _BFS(q, visited);
- }
- }
- cout << endl;
- }
- void _BFS(queue<int>& q, vector<bool>& visited)
- {
- while (!q.empty())
- {
- size_t index = q.front();
- q.pop();
- if (visited[index] == true)
- continue;
- visited[index] = true;
- cout << _v[index] << " ";
-
- pNode pCur = _linkEdges[index];
- while (pCur)
- {
- if (visited[pCur->_dst] == false)
- q.push(pCur->_dst);
- pCur = pCur->_pNext;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。