C++之最短路径算法(无权最短路径)

 无权的最短路径的算法与广度优先搜索算法的实质是一样的。层层递推(每次路径值加一),层层被赋值,就像树的层序遍历。

C++之最短路径算法(无权最短路径)_第1张图片

 

#include
#include
#include
#include
#include
const size_t InFinity = 999;
struct Vertex {
	size_t   vertexnumber;
	bool*    visited;  //对访问过的vertex进行标记
	size_t*  dis;      //startvertex 到 每一个vertex的路径值
};
class Graph {
public:
	Graph(const size_t _vertexnumber) :verptr(std::make_unique()), lists(new std::list[_vertexnumber]()), queu(new std::queue[_vertexnumber]()) {
		verptr->visited = new bool[_vertexnumber]();
		verptr->dis = new size_t[_vertexnumber]();
		verptr->vertexnumber = _vertexnumber;
		for (int i = 0; i < verptr->vertexnumber; ++i)
			verptr->dis[i] = InFinity;
	}
	~Graph() {
		if (verptr->dis && verptr->visited && queu && lists) {
			delete[] verptr->dis;
			delete[] verptr->visited;
			delete[] queu;
			delete[] lists;
		}
		else
			throw std::out_of_range("Out of MemorySpace!!");
	}

	void AddEdge(const size_t v, const size_t w);
	void UnWeight(size_t v);

private:
	std::unique_ptrverptr;
	std::list*lists;
	std::queue*queu;
};

void Graph::AddEdge(const size_t v, const size_t w) {
	lists[v].push_back(w);
}

void Graph::UnWeight(size_t v) {
	auto v_ = v;
	verptr->dis[v] = 0;
	queu->push(v);
	while (!queu->empty()) {
		v = queu->front();
		queu->pop();
		auto beg = lists[v].begin();
		while (beg != lists[v].end()) {
			verptr->visited[v] = true; 
			if (verptr->dis[*beg]==InFinity) {
				verptr->dis[*beg] = verptr->dis[v] + 1;
				queu->push(*beg);
			}
			++beg;
		}
	}
	for (int i = 0; i < verptr->vertexnumber; ++i) {
		std::cout << v_ << " to " << i << "  MinPath:  " << verptr->dis[i] << std::endl;
	}
}

int main(void)
{
	const size_t vertexnumber = 7;
	Graph graph(vertexnumber);
	graph.AddEdge(0, 1);
	graph.AddEdge(0, 2);
	graph.AddEdge(0, 3);
	graph.AddEdge(1, 3);
	graph.AddEdge(1, 4);
	graph.AddEdge(2, 5);
	graph.AddEdge(3, 2);
	graph.AddEdge(3, 5);
	graph.AddEdge(3, 6);
	graph.AddEdge(3, 4);
	graph.AddEdge(4, 6);
	graph.AddEdge(6, 5);
	graph.UnWeight(0);

	system("pause");
}

 

 C++之最短路径算法(无权最短路径)_第2张图片

你可能感兴趣的:(算法,c++)