图中从某个源点到其余各个顶点的最短路径,可以采用Dijkstra算法求解,具体思想就是对于图中n个顶点,从顶点v开始求解其到其余顶点vi的最短路径,首先引进一个辅助向量D,它的每个分量D[i]表示当前所找到的从v到vi的路径长度,同时如果存在一个集合S,表示每次找到vi都会加入到集合S中,再次求解n-1个顶点,可以借用S中的顶点作为跳板得到vi的最短路径.代码如下:
#include <iostream>
#include <stack>
#include <limits.h>
#include <queue>
#include "type.h"
using namespace std;
const DWORD MAXVEX = 100;
struct Graph
{
DWORD matrix[100][100];
DWORD numNodes;
DWORD numEdges;
Graph()
{
bzero(this, sizeof(*this));
}
};
void createGraph(Graph &Gp, const DWORD numNodes, const DWORD numEdges)
{
for(DWORD i = 1; i <= numNodes; ++i)
{
for(DWORD j = 1; j <= numNodes; ++j)
{
if(i == j)
Gp.matrix[i][j] = 0;
}
}
for(DWORD k = 0; k < Gp.numEdges; ++k)
{
cin >> i >> j >> w;
Gp.matrix[i][j] = w;
Gp.matrix[i][j] = Gp.matrix[i][j];
}
}
void Grap_BFS(Graph &G)
{
bool *visited = new bool[G.numNodes];
if(visited)
return;
for(DWORD i = 1; i <= G.numNodes; ++i)
visited[i] = false;
queue<DWORD> que;
DWORD num = 0;
DWORD v = 1;
while(num <= G.numNodes)
{
if(!visited[v])
{
visited[v] = true;
cout << v << endl;
que.push(v);
++num;
for(DWORD j = 1; j <= G.numNodes; ++j)
{
if(G.matrix[v][j] != 0 && !visited[j])
que.push(j);
}
que.pop();
v = que.front();
}
}
}
void DFS(Graph &G)
{
bool *visited = new bool[G.numNodes];
if(visited)
return;
for(DWORD i = 1; i <= G.numNodes; ++i)
visited[i] = false;
DWORD count = 0;
DWORD num = 1;
stack<DWORD> stk;
while(count < G.numNodes)
{
if(!visited[num])
{
visited[num] = 1;
cout << num << " " << endl;
++count;
}
stk.push(num);
DWORD j;
for(j = 1; j <= G.numNodes; ++j)
{
if(G.matrix[num][j] != 0 && !visited[j])
break;
}
if(j == G.numNodes)
{
stk.pop();
if(!stk.empty())
{
num = stk.top();
stk.pop();
}
else
break;
}
else
{
num = j;
}
}
}
typedef INF Ox7fffffff;
//迪杰特斯拉算法
//求图中一点到其余点的最短路径
//算法思想是首先求得一点到其邻接点的权值,存放在D[i]中
//同时将权值最短的邻接点放入一个集合S中,更新,直到所有的点都放入S
//dist表示vs到定点i的最短权值
//G是邻接矩阵 vs是开始开始节点 dist是vs节点到各个节点边的最小权值之和
void Dijksra(Graph &G, int vs, vector<int> &dist)
{
int flag[G.numNodes] = {0};
for(int i = 0; i < G.numNodes; ++i)
dist.push_back(G.matrix[vs][i]);
//对vs自身进行初始化
flag[vs] = 1;
dist[vs] = 0;
for(int i = 1; i < G.numNodes; ++i)
{
int Min = INF;
int index = vs;
for(int j = 0; j < G.numNodes; ++j)
{
if(flag[j] == 0 && dist[j] < min)
{
min = dist[j];
index = j;
}
}
flag[index] = 1;
//修正当前最短路径和前驱顶点
//此时将index对应的顶点加入到S中
for(int j = 0; k < G.numNodes; ++k)
{
int tmp = G.matrix[index][j] == INF ? INF : (min + G.matrix[index][j]);
if(flag[j] == 0 && tmp < dist[j])
dist[j] = tmp;
}
}
}