I am trying to create an adjacency matrix from a graph file.
I need to read in a text file containing the number of vertices, then lists the graph format
Ex:
5
0 3 2
1 0 2
1 2 2
1 4 1
The first column of numbers is for the id of source vertex, the second column is for the id of target vertex, and the third column is the weight of edge
So this should return the matrix
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
So far I have read the text file and gotten the number of vertices but I'm not sure on what to do from here.
My current code:
#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;
}