template <typename Tv, typename Te>
template <typename PU>
void GraphMatrix<Tv, Te>::pfs(int s, PU prioUpdater)
{
reset(); int v = s;
do {
if (UNDISCOVERED == status(v))
{
PFS(v, prioUpdater);
}
} while (s != (v = (++v%__n)));
}
template <typename Tv, typename Te>
template <typename PU>
void GraphMatrix<Tv, Te>::PFS(int s, PU prioUpdater)
{
priority(s) = 0; status(s) = VISITED; parent(s) = -1;
while (true)
{
for (int w = firstNbr(s); -1 < w; w = nextNbr(s, w))
{
prioUpdater(this, s, w); //因为这个函数是GraphMatrix这个类里的,所以this表示的是这个类对象的实体
}
for (int shortest = INT_MAX, w = 0; w < __n; w++)
{
if (UNDISCOVERED == status(w)) //从尚未加入遍历树的顶点中
{
if (shortest > priority(w)) //选出下一个
{
shortest = priority(w);
s = w; //选择优先级最高的顶点
}
}
}
if (VISITED == status(s)) break; //直至所有顶点均已加入
status(s) = VISITED;
type(parent(s), s) = TREE;
}
}
我分别定义了两个优先器,决定是一直走,还是把当前的邻居都走完
template <typename Tv, typename Te>
struct BfsPU
{
virtual void operator()(GraphMatrix<Tv, Te> *g, int uk, int v)
{
if (g->status(v) == UNDISCOVERED)
{
if (g->priority(v) > g->priority(uk) + 1)
{
g->priority(v) = g->priority(uk) + 1;
g->parent(v) = uk;
} //如此效果等同于只要有一个邻居的优先级大于uk,则选择uk作为其父节点
}
}
};
template <typename Tv, typename Te>
struct DfsPU
{
virtual void operator()(GraphMatrix<Tv, Te> *g, int uk, int v)
{
if (g->status(v) == UNDISCOVERED)
{
if (g->priority(v) > g->priority(uk) - 1)
{
g->priority(v) = g->priority(uk) - 1;
g->parent(v) = uk;
//发现的邻居一个比一个优先的。就会一直走
} //如此效果等同于只要有一个邻居的优先级大于uk,则选择uk作为其父节点
}
}
};