树的广度优先,深度优先-----------好的代码

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作为其父节点
		}
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值