1. 程式人生 > >三種存圖方式(鄰接矩陣,鄰接表,鏈式前向星)

三種存圖方式(鄰接矩陣,鄰接表,鏈式前向星)

#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include <iostream>
using namespace std;
const int MAXN=10;
struct node
{
    int to,cost;
};
int a[MAXN][MAXN];
vector<node> v[MAXN];
int n,m=5;  //m個頂點
void init1()  //鄰接矩陣
{
    int i,j;
    for(i=1;i<=n;i++)
    {
        int x,y,z=1;  //z為權值,也可自己輸入
        cin>>x>>y;
        a[x][y]=z;
    }
    for(i=1;i<=m;i++)
    {
        for(j=1;j<=m;j++)
           cout<<a[i][j]<<" ";
        cout<<endl;
    }
    return ;
}
void init2()   //鄰接表
{
    int i,j;
    for(i=1;i<=n;i++)
    {
        int x;
        node y;
        y.cost=1;   //cost為權值
        cin>>x>>y.to;
        v[x].push_back(y);
    }
    for(i=1;i<=m;i++)
    {
        for(j=0;j<v[i].size();j++)
            cout<<i<<" "<<v[i][j].to<<" "<<v[i][j].cost<<endl;
    }
    return ;
}
int cnt=0;
int head[MAXN];
struct Node
{
    int to,cost,next;
}edge[MAXN];
void init3()   //鏈式前向星
{
    int i,j;
    int start,endd,cost;
    memset(head,-1,sizeof(head));
    for(i=0;i<n;i++)
    {
        cost=1;
        scanf("%d%d",&start,&endd);
        edge[cnt].to=endd;
        edge[cnt].cost=cost;
        edge[cnt].next=head[start];
        head[start]=cnt++;
    }
    for(start=1;start<=m;start++)
        for(i=head[start];i!=-1;i=edge[i].next)
            printf("(%d %d)--> %d\n",start,edge[i].to,edge[i].cost);
    return ;
}
int main()
{
    cin>>n;   //輸入n組資料
    init1();  //鄰接矩陣
    init2();  //鄰接表
    init3();  //鏈式前向星
    return 0;
}




 

樣例:
7
1 2
2 3
3 4
1 3
4 1
1 5
4 5
鄰接矩陣執行結果
0 1 1 0 1
0 0 1 0 0
0 0 0 1 0
1 0 0 0 1
0 0 0 0 0
鄰接表執行結果
1 2 1
1 3 1
1 5 1
2 3 1
3 4 1
4 1 1
4 5 1
鏈式前向星執行結果
(1 5)-->1
(1 3)-->1
(1 2)-->1
(2 3)-->1
(3 4)-->1
(4 5)-->1
(4 1)-->1