最短路简化版的两种解法

#include <iostream>
#include <vector>
#include<queue>
#include <cstring>
using namespace std;

class Graph {
private:
	int n;
	vector<int> *v;//邻接表
	bool *visited;//访问标志

public:
	Graph(int input_n) {
		n = input_n;
		v = new vector<int>[n];
		visited = new bool[n];
		memset(visited, 0, sizeof(bool)*n);
	}
	~Graph() {
		delete[] v;
		delete[] visited;

	}
	void insert(int x, int y) {
		v[x].push_back(y);
		v[y].push_back(x);
	}
	void bfs_1(int start_vertex) {
		queue<int> bfs_queue;
		vector<int> level_vertex(n);//存储每个节点的层数
		int last, nextlast;//最右元素和下一层最右元素
		last = start_vertex;
		int level = 1;//层数
		bfs_queue.push(start_vertex);//入队
		visited[start_vertex] = true;
		while (!bfs_queue.empty()){
			int vertex = bfs_queue.front();
			bfs_queue.pop();//访问后弹出
			for (int adj_vertex : v[vertex]){
				if (!visited[adj_vertex]){
					visited[adj_vertex] = true;
					nextlast = adj_vertex;//跟踪,直到最右元素
					level_vertex[adj_vertex] = level;
					bfs_queue.push(adj_vertex);
				}
			}
			if (vertex == last){//当访问到当前层中的最右元素时,表示该换行了,到下一层
				last = nextlast;
				level++;
			}
		}
		for (int i = 0; i < n - 1; i++){
			cout << level_vertex[i] << endl;
		}
		cout << level_vertex[n - 1];
	}

	//第二种方法
	void bfs_2(int start_vertex){
		queue<int> bfs_queue;
		vector<int> level_vertex(n);//存储每个节点的层数
		bfs_queue.push(start_vertex);//入队
		visited[start_vertex] = true;
		while (!bfs_queue.empty()){
			int vertex = bfs_queue.front();
			bfs_queue.pop();//访问后弹出
			for (int adj_vertex : v[vertex]){
				if (!visited[adj_vertex]){
					visited[adj_vertex] = true;
					level_vertex[adj_vertex] = level_vertex[vertex] + 1; //更新层数
					bfs_queue.push(adj_vertex);
				}
			}
		}
		for (int i = 0; i < n - 1; i++){ //按照节点序号输出
			cout << level_vertex[i] << endl;
		}
		cout << level_vertex[n - 1];
	}
};
int main() {
	int n, m, c;//图的顶点数,无向边的数量,广搜的起点
	cin >> n >> m >> c;
	Graph g(n);
	for (int i = 0; i < m; ++i) {
		int x, y;
		cin >> x >> y;//顶点的编号为1~n;
		g.insert(x-1, y-1);//插入时,内部的编号为0~n-1
	}
	g.bfs_2(c-1);//对起点进行广度搜索,以起点为第零层,不断向外扩层,最终按节点的序号输出每个节点所在的层数。
	system("pause");
	return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值