【发布时间】:2018-12-03 03:10:24
【问题描述】:
我正在尝试从图形文件创建邻接矩阵。
我需要读入一个包含顶点数的文本文件,然后列出图形格式
例如:
5
0 3 2
1 0 2
1 2 2
1 4 1
第一列数字是源顶点的id,第二列是目标顶点的id,第三列是边的权重
所以这应该返回矩阵
0 2 0 2 0
2 0 2 0 1
0 2 0 0 0
2 0 0 0 0
0 1 0 0 0
到目前为止,我已经阅读了文本文件并获得了顶点的数量,但我不确定从这里开始做什么。
我当前的代码:
#include <stdio.h>
#include <stdlib.h>
int main (){
printf("Enter the file contianing the graph\n");
char filename[20];
FILE *myFile;
scanf("%s",filename);
myFile = fopen (filename,"r");
int number_of_nodes, number_of_edges;
int source_id[100], target_id[100], weight[100];
int matrix[100][100];
int i;
if (myFile == NULL){
printf("File not found! Exiting...\n");
return -1;
}
else{
fscanf(myFile, "%d", &number_of_nodes);
printf("There are %d vertices.\n", number_of_nodes);
for(i = 0; i < (sizeof (source_id) / sizeof ( source_id[0] )); i++)
{
if( fscanf(myFile, "%d %d %d", &source_id[i], &target_id[i], &weight[i]) != 3)
break;
}
number_of_edges = i;
for (i = 0; i<99;i++){
for (int j = 0; j< 99; i++){
matrix[i][j]=0;
}
}
for (i = 0; i < number_of_edges; i++){
int x = source_id[i];
int y = target_id[i];
matrix[x][y] = weight[i];
matrix[y][x] = weight[i];
}
for (int y = 0; y < (number_of_nodes-1); y++){
for (int x = 0; x < (number_of_nodes -1); x++){
printf(matrix[x][y]);
printf(" \n");
}
}
}
fclose(myFile);
return 0;
}
【问题讨论】:
-
文件第一行是节点数还是最大节点ID?如果是第一个,那么为什么是 4,而不是 5?为什么元素 [4,4] 被设置为 1?
-
对不起,应该是5,我放错了4
-
当然最好检查语句 fscanf(myFile,"%d,",&numberArray[i]); 的返回码。此 IO 操作有时可能会失败...
-
@KrassiEm 你这是什么意思/我该如何改进它?
标签: c