鄰接矩陣到鄰接表
5000(ms)
10000(kb)
2341 / 5552
假設無向圖G採用鄰接矩陣存儲,編寫一個算法輸出鄰接表。
輸入
第一行爲一個整數n,表示頂點的個數(頂點編號爲0到n-1),接下來是爲一個n*n大小的整數矩陣,表示圖的鄰接關係。數字爲0表示不鄰接,1表示鄰接。
輸出
輸出圖G的鄰接表。第一行表示頂點0可直接到達的頂點編號。其他行定義相同。
樣例輸入
5 0 1 0 1 1 1 0 1 1 0 0 1 0 1 1 1 1 1 0 1 1 0 1 1 0
樣例輸出
134 023 134 0124 023
#include<stdio.h>
#include<malloc.h>
struct ArcNode//儲存數據以及下一個結點的結構體
{
int data;
struct ArcNode *next;
};
struct HeadNode//儲存頭結點的結構體
{
struct ArcNode *head;
};
void MatGraph(int n,int edges[100][100])//儲存鄰接矩陣
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
scanf("%d",&edges[i][j]);
}
}
void CreateAdj(int n,int edges[100][100],struct HeadNode VNode[])//轉換矩陣爲鏈表
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(edges[i][j]==1)
{
struct ArcNode *p;
p=(struct ArcNode *)malloc(sizeof(struct ArcNode));
p->data=j;
p->next=NULL;
if(VNode[i].head==NULL) VNode[i].head=p;//如果該序號對應的頭結點爲空,則儲存頭結點
else//否則從頭結點往後尋找最後一個結點
{
struct ArcNode *q=VNode[i].head;
while(q->next!=NULL) q=q->next;
q->next=p;//連接在最後的結點
}
}
}
}
}
void DispAdj(struct HeadNode VNode[],int n)//輸出鄰接鏈表
{
for(int i=0;i<n;i++)
{
if(VNode[i].head!=NULL)
{
struct ArcNode *p=VNode[i].head;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
}
printf("\n");
}
}
int main()
{
int n;
scanf("%d",&n);
int edges[100][100];
MatGraph(n,edges);
HeadNode VNode[n];
for(int i=0;i<n;i++) VNode[i].head=NULL;
CreateAdj(n,edges,VNode);
DispAdj(VNode,n);
}