下面是实现的代码,需要借助队列来完成:
// 图的广度优先遍历
void BFS(const V& v)
{
queue q;
//标记是否已经遍历,遍历过为true
vector 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& q, vector& 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;
}
}
}
// 图的深度优先遍历
void DFS(const V& v)
{
size_t index = GetDevOfV(v);
vector visited(_v.size(), false);
_DFS(index, visited);
for (size_t i = 0; i < _v.size(); i++)
{
if (visited[i] == false)
_DFS(i, visited);
}
cout << endl;
}
void _DFS(int index, vector& visited)
{
cout << _v[index] << " ";
visited[index] = true;
pNode pCur = _linkEdges[index];
while (pCur)
{
if (visited[pCur->_dst] == false)
_DFS(pCur->_dst, visited);
pCur = pCur->_pNext;
}
}
// 最小生成树---克鲁斯卡尔算法;
typedef Graph Self;
typedef Node LinkEdge;
Self Kruskal()
{
Self g; //新建一个图
g._v = _v; //
g._linkEdges.resize(_v.size());
vector edges;
for (size_t i = 0; i > _v.size(); i++)
{
LinkEdge* pCur = _linkEdges[i];
while (pCur)
{
if (IsDirect || (!IsDirect&&pCur->_src < pCur->_dst)) //保存边的权值
edges.push_back(pCur);
pCur = pCur->_pNext;
}
}
class Compare
{
public:
bool operator()(const LinkEdge* left, const LinkEdge* right)
{
return left->_weight < right->_weight;
}
};
sort(edges.begin(), edges.end(), Compare());
size_t count = _v.size() - 1;//从前往后取n-1条边
UnionFind u(_v.size());
for (size_t i = 0; i < edges.size(); i++)
{
LinkEdge* pCur = edges[i];
size_t srcRoot = u.FindRoot(pCur->_src);
size_t dstRoot = u.FindRoot(pCur->_dst);
if (srcRoot != dstRoot) //两个节点不在一个集合,加边
{
g.AddEdge(pCur->_src, pCur->_dst, pCur->_weight);
if (!IsDirect) //有向图
g.AddEdge(pCur->_dst, pCur->_src, pCur->_weight);
u.Union(pCur->_src, pCur->_dst);//合并
count--;
if (count == 0)
break;
}
}
if (count > 0)
cout << "最小生成树非法" << endl;
return g;
}