Adjacency Matrix

Nov 20, 2014 at 9:20pm
Hi,
I have an input file with string names of vertices to make a graph (adjacency matrix). How can I make it so the string names correspond to numbers to go with the rows and columns of the matrix?

For example, say the file contains:
V1
V2
V3
...

I want it to be like
1
2
3
4
5
      V1  V2   V3
V1    0    0    0
V2    0    0    0
V3    0    0    0
...

And then have (V1,V1) mean (1,1) in the matrix.

And if I wanted a weighted edge between the two vertices I'd have something like addEdge(V1, V3, weight), where V1 and V3 correspond ints of (1,3) for (i,j) in the matrix.
Last edited on Nov 20, 2014 at 9:50pm
Nov 20, 2014 at 10:44pm
Please help :(
Nov 20, 2014 at 10:56pm
The way you represent things with text only matters when you are either reading or writing it. Manipulating stuff inside the program doesn't need it.
Nov 20, 2014 at 11:01pm
I'm making a graph using an adjacency matrix. It takes two input files, one of vertices, and one of edges.

If I have an edge like: V192 and V284, how would it know where to edit the matrix to show there's an edge there?

I want to make it so a vertex corresponds to say, for example, 5 and 3 for V192 and V284, respectively. How else would it know to go to (5,3) in the matrix?
Nov 21, 2014 at 12:24am
Ah, your matrix has a lot of rows and columns? I presume it is fairly sparse?

Use a std::map with a custom 'edge' type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct edge
{
  int u, v;
  edge(): u(), v() { }
  edge( int u, int v ): u( u ), v( v ) { }

  bool operator < ( const edge& e ) const 
  {
    return (u < e.u) ? true
         : (u == e.u) ? (v < e.v)
         : false;
  }
};

typedef std::map <edge, bool> adjmatrix;

Now all you have to do is strip the 'V' from the vertex name to get it's index, and use the indices to lookup an edge.

You can iterate through the edges too.

Hope this helps.
Nov 21, 2014 at 1:00am
Sorry I should have said the identifiers for vertices can be any string of max length 20.
Nov 21, 2014 at 2:55am
Well, replace int with std::string.
Topic archived. No new replies allowed.