Search code examples
javagraph-theoryadjacency-matrix

Coding the adjacency matrix for a graph in java and counting triangles


I have very little programming experience, so for practice I wanted to "construct" a graph in java by coding its adjacency matrix with a two dimensional array. Specifically, I want to construct the red graph found here https://www.cut-the-knot.org/arithmetic/combinatorics/Ramsey44.shtml, but what I coded gives me less edges in the matrix than there should be. Here is what I have so far:

public static int[][] createGraph(){

int[][] graph = new int[17][];
for(int i=0; i<17; i++){
  graph[i] = new int[i+1];
}

for(int i = 0; i<17; i++){
  for(int j = 0; j<=i; j++){
    if(i-j == 1 || i-j == 2 || i-j == 4 || i-j == 8){
      graph[i][j] = 1;

    }
  }
}
return graph;

There are 68 edges in the graph, so there should be 68 1's in the lower triangle of the adjacency matrix, which is what I'm trying to construct, but when I manually count them, when I print it, I find 59 of them. I don't know why there are edges missing. I'm guessing that assigning an edge based on the difference between the column number and the row number is not the same as the "difference between vertices" as in the website. What should I do instead?

Also my next exercise will be to count the number of triangles in the graph. I have an idea on how to do that, but could I get a hint?


Solution

  • You are restricting the construction to one triangle of the matrix but you may not restrict the construction of index pairs for connected nodes some other part of the matrix, i.e., the diagonal "strips" with |i-j| <= 8. Therefore:

    if(i-j == 1 || i-j == 2  || i-j == 4  || i-j == 8 ||
       i-j == 9 || i-j == 13 || i-j == 15 || i-j == 16){