-1

I am given a input file that contains numbers like this:

3 (searching for value 3 in graph)

5 (number of vertices in graph)

0 0 (vertex 0 has value has value 0)

2 (add 2 edges from vertex 0)

1 ( add an edge from vertex 0 to vertex 1)

2 ( add an edge from vertex 0 to vertex 2)

1 1 (vertex 1 has value 1)

2 (add 2 edges from vertex 1)

3 (add an edge from vertex 1 to vertex 3)

4 (add an edge from vertex 1 to vertex 4)

2 2 (vertex 2 has value 2).......

I want to create an adjacency matrix using the given numbers in the file, but I am unsure of how to do this. How would I make sure I'm just filling the matrix with either 0's or 1's depending on whether or not there is an existing edge? I don't think I can just read in each file one-by-one because not all of the lines detail info about the edges. Any insight would be greatly appreciated. Thanks!

S. James
  • 77
  • 5

2 Answers2

0

Since you know almost immediately what the size of the matrix is, you can allocate a adjacency matrix of the required size, then go through the file, adding edges as you encounter them. An outline of the code might look something like:

std::ifstream in;

// Read the target and number of nodes.
int target;
int num_nodes;

in >> target >> num_nodes;

// Whatever matrix data type you are using.
matrix adj_matrix(num_nodes, num_nodes);

// Process each vertex.
for (int i = 0; i < num_nodes; ++i) {
    int node;
    int value;
    in >> node >> value;

    // Figure out how many edges the vertex has.
    int num_edges;
    in >> num_edges;

    // Process each edge and add it to the matrix.
    for (int j = 0; j < num_edges; ++j) {
        int other_node;
        in >> other_node;

        // Add the dependency both ways to the matrix.
        adj_matrix[node][other_node] = true;
        adj_matrix[other_node][node] = true;
    }
}
ajshort
  • 3,684
  • 5
  • 29
  • 43
0

Assuming your matrix Edges is filled with zeros, you can do something like that:

  1. Read the first number and store the value somewhere (I don't understand what the first number is for, actually).
  2. Read the second number and store it in n.
  3. While there is no end of line do lines 4..8
  4. Read the number and store it in variable v (number of vertex)
  5. Read the number and store it in Values[v] (value of current vertex)
  6. Read the number and store it in e (number of edges from v'th vertex.
  7. For i from 1 to e do 8.
  8. Read v1 and put Edges[v,v1]=1 (and maybe E[v1,v], if E has to be symmetric).
Mateo
  • 138
  • 1
  • 7