/* 邻接矩阵、构造有向图 */
#include <cstdio>
#include <cstdlib>
const int maxv = 20;
//INF定义为无穷大,表示不连通
const int INF = 9999;
bool visited[maxv];
/* MGraph类(邻接矩阵构建图类)*/
class MGraph
{
private:
typedef struct
{
int edges[maxv][maxv];
int n,e;
}Graph;//定义图类型
Graph *g;//定义图类型变量g
public:
MGraph()//构造函数内,初始化成员g
{
g = (Graph*)malloc(sizeof(Graph));
}
/* 构建图(邻接矩阵) */
void create_MGraph()
{
printf("输入顶点数,边数(n e): ");
scanf("%d%d",&g->n,&g->e);
int i,j,w;
for(int i = 0; i < g->n; i++)
{
for(int j = 0; j < g->n; j++)
{
g->edges[i][j] = INF;
}
}
printf("输入边及权(i j weight):\n");
for(int count = 0; count < g->e; count++)
{
scanf("%d%d%d",&i,&j,&w);
g->edges[i][j] = w;
}
}
/* 打印图(邻接矩阵) */
void print_MGraph()
{
for(int i = 0; i < g->n; i++)
{
for(int j = 0; j < g->n; j++)
{
printf(" %4d ",g->edges[i][j]);
}
printf("\n");
}
}
/* 深度优先遍历 */
void dfs(int v)
{
printf("V%d ",v);
visited[v] = 1;
int w;
for(w = 0; w < g->n; w++)
if(g->edges[v][w]!=0 && visited[w] == 0)
dfs(w);
}
/* 广度优先遍历 */
void bfs(int v)
{
int qu[maxv];
int front = 0,rear = 0;
printf("V%d ",v);
visited[v] = 1;
rear = (rear+1) % maxv;
qu[rear] = v;
int w;
while(front != rear)
{
front = (front+1) % maxv;
w = qu[front];
for(int i = 0; i < g->n; i++)
{
if(g->edges[w][i] != 0 && visited[i] == 0)
{
printf("V%d ",i);
visited[i] = 1;
rear = (rear+1) % maxv;
qu[rear] = i;
}
}
}
}
/* 输出任意顶点V0,到其他顶点的最短路径 */
void Dispath(int dist[],int path[],int S[],int v)
{
int k,d;
for(int i = 0; i < g->n; i++)
if(S[i] == 1 && i != v)
{
printf("V%d->V%d的路径长度为: %d\n",v,i,dist[i]);
k = path[i];
if(k == -1)
printf("无路径\n");
}
}
/* Dijkstra算法,求最短路径 */
void Dijkstra(int v)
{
int dist[maxv],path[maxv];
int S[maxv];
int mindist,u;
for(int i = 0; i < g->n; i++)
{
dist[i] = g->edges[v][i];
S[i] = 0;
if(g->edges[v][i] < INF)
path[i] = v;
else
path[i] = -1;
}
S[v] = 1,path[v] = 0;
for(int i = 0; i < g->n; i++)
{
mindist = INF;
for(int j = 0; j < g->n; j++)
{
if(S[j] == 0 && dist[j] < mindist)
{
u = j;
mindist = dist[j];
}
}
S[u] = 1;
for(int j = 0; j < g->n; j++)
{
if(S[j] == 0)
{
if(g->edges[u][j] < INF && dist[u] + g->edges[u][j] < dist[j])
{
dist[j] = dist[u] + g->edges[u][j];
path[j] = u;
}
}
}
}
Dispath(dist,path,S,v);
}
/* g->n为MGraph类私有成员
只能通过函数访问,获得图的边数n */
int MGraph_n()
{
return g->n;
}
};
int main()
{
MGraph mgraph;//MGraph类,实例化对象mgarph
//freopen("data.txt","r",stdin);
printf("create MGraph(邻接矩阵类)\n");
mgraph.create_MGraph();
printf("---------------------\n");
printf("print MGraph(邻接矩阵类)\n");
mgraph.print_MGraph();
printf("---------------------\n");
/* 深度优先遍历 */
for(int i = 0; i < mgraph.MGraph_n(); i++)
visited[i] = 0;
printf("dfs: ");
mgraph.dfs(0);
printf("\n");
/* 广度优先遍历 */
for(int i = 0; i < mgraph.MGraph_n(); i++)
visited[i] = 0;
printf("bfs: ");
mgraph.bfs(0);
printf("\n");
printf("---------------------\n");
/* 输出任意顶点V0,到其他顶点的最短路径 */
mgraph.Dijkstra(0);
system("Pause");
return 0;
}
/*
测试用例:
//(第一组)
4 4
0 1 9
1 2 8
0 2 7
3 2 6
//(第二组)
5 7
0 1 9
1 2 8
2 3 7
3 4 6
0 2 5
0 3 4
0 4 3
*/
邻接矩阵、构造有向图
最新推荐文章于 2024-06-20 22:46:18 发布