您的位置:首页 > 其它

最短路简化版的两种解法

2017-08-09 19:00 465 查看
#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>
;
visited = new bool
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: