无向图就是没有方向区别的图。在无向图中,(x, y) 和 (y, x) 是一样的,都表示为 x <--> y

template <class TPV>
void clearPointerV(std::vector<TPV*>& pv)
{
	for (TPV*& c : pv)
	{
		if (c) delete c;

		c = nullptr;
	}

	pv.clear();
}

template<class TMV>
struct MyVertex
{
	TMV value;
	std::vector<MyVertex<TMV>*> nexts;//no delete

	MyVertex(const TMV& v) :value(v) {};
};

template<class TMUG>
class MyUndirectedGraph
{
private:
	std::vector<MyVertex<TMUG>*> vertexs;
public:
	MyUndirectedGraph() = default;

	~MyUndirectedGraph()
	{
		clearPointerV(vertexs);
	}

	void clear()
	{
		clearPointerV(vertexs);
	}
	unsigned int size()
	{
		unsigned int edgeN = 0;

		for (auto& v : vertexs) edgeN += v->nexts.size();
		
		return (edgeN / 2);//双向连接
	}
	void addEdge(TMUG A, TMUG B)
	{
		MyVertex<TMUG>* vA = nullptr;
		MyVertex<TMUG>* vB = nullptr;

		for (auto& v : vertexs)
		{
			if (v->value == A)
			{
				for (const auto& n : v->nexts) if (n->value == B) return;

				vA = v;
			}
			else if (v->value == B)
			{
				for (const auto& n : v->nexts) if (n->value == A) return;

				vB = v;
			}
		}

		if (!vA)
		{
			vA = new MyVertex<TMUG>(A);

			vertexs.push_back(vA);
		}
		if (!vB)
		{
			vB = new MyVertex<TMUG>(B);

			vertexs.push_back(vB);
		}
		
		if (vA && vB)
		{
			//双向连接 nexts.size()+=2
			vA->nexts.push_back(vB);
			vB->nexts.push_back(vA);
		}
	}
};

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐