c - 图:用于邻接矩阵
问题描述
我必须编写一个程序,它将以邻接表和邻接矩阵的形式显示图形结果。我已经通过 YT 上的教程指导自己如何实现邻接列表,并使用当前存储的数据(用户正在介绍自己,例如节点数、边数、边连接的边数以及哪一个)我想知道/了解如何使用已经存储的数据来构建邻接矩阵。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void read_graf(struct node *ad[], int no_of_nodes);
void print_graf(struct node *ad[], int no_of_nodes);
int main()
{
int op;
int i,j,k, nodes;
begin:
printf("Type in the number of edges: ");
scanf("%d", &nodes);
struct node *adj[nodes];
for (i=0;i<nodes;i++)
adj[i] = NULL;
read_graf(adj,nodes);
print_graf(adj,nodes);
printf("\nDo you want to try again? 1 for yes and 0 for no: ");
scanf("%d", &op);
if (op==1)
goto begin;
else
{
printf("Thank you for visiting! :)");
exit(0);
}
return 0;
}
void read_graf(struct node *ad[], int no_of_nodes)
{
struct node *new_node;
int i,j,k, val;
for (i=0;i<no_of_nodes;i++)
{
struct node *last= NULL;
printf("\n To how many edges is edge %d connected to: ", i+1);
scanf("%d", &k);
for (j=0;j<k;j++)
{
printf("To which edges is it connected : ");
scanf("%d", &val);
new_node = (struct node *)malloc(sizeof(struct node*));
new_node->data = val;
new_node->next = NULL;
if(ad[i]==NULL)
ad[i]= new_node;
else
last->next = new_node;
last = new_node;
}
}
}
void print_graf(struct node *ad[], int no_of_nodes)
{
struct node *ptr = NULL;
int i,j;
for(i=0;i<no_of_nodes;i++)
{
ptr = ad[i];
printf("\n x%d : ", i+1);
while(ptr != NULL)
{
printf("%d,\t", ptr->data);
ptr = ptr->next;
}
printf("0");
}
}
解决方案
如果您只需要打印出邻接矩阵并假设 a1
表示节点i和节点j之间的连接,则只需稍微修改print_graf
函数内部的内部循环。
void print_as_mat(struct node *ad[], int no_of_nodes)
{
struct node *ptr = NULL;
for(int i = 0; i < no_of_nodes; ++i)
{
ptr = ad[i];
// Loop over all the possible nodes
for(int j = 0; j < no_of_nodes; ++j)
{
if ( ptr && ptr->data == j ) {
// ^^^^^^^^^^^^^^ Check if the index correspond to the
// current node in the adjacency list.
printf(" 1");
// update the current node in the list, but only here.
ptr = ptr->next;
}
else {
printf(" 0");
}
}
// The row is completed.
putchar('\n');
}
}
推荐阅读
- javascript - VUE JS 组件正在附加现有的刀片内容
- reactjs - 如何使用 Jest 在 react useState 中为状态编写状态案例
- swift - 如何在macOS(OSX)Swift中获取当前选项卡的FavIcon
- sql - 需要在 sql server 中返回一个有 start 和 END 的 ID
- java - 为mingw / ios / linus /其他源集导入java lib的解决方法?
- html - 将其定位为绝对后,我的 div 消失了
- android - 无法从 Google Play 控制台中的实时开发人员通知发送测试通知
- java - MediaPlayer.create(this,audio_file)
- delphi - 无法使用 Delphi Indy 控件连接到 https 站点
- php - 将数组排序为升序