0

I have an directed graph that is represented by an adjacency matrix, where a -1 is indicative of a disconnect between two nodes.

My goal is to find and sum up each source node in the graph (i.e. any node that contains to edges coming into it).

I currently have a O(n^2) routine that checks each cell of a given row, and at each cell flips the indices to see if there exists an edge coming into the node I'm currently looking at.

I have a int used to keep track of how many source nodes I've come across so far, and a boolean that becomes marked every time I come across a node that isn't a source node.

Throughout continuous testing of my code, I found that each time returned me 0 source nodes, though I know my graph contains at least 1. I've written the following method...

In this method, size represents the number of nodes that exist in the graph and m is the adjacency matrix.

public int numSources() {
    int sources = 0;
    boolean isSource = true;
    for( int i = 0; i < size; i++ ) {
        for( int j = 0; j < size; j++ ) {
            if( m[j][i] != -1) {
                isSource = false;
                break;
            }
        }
        if( isSource ) {
            sources++;
        } else {
            isSource = true;
        }
    }
    return sources;
}

I have a file with each line consisting of int int int where the first two ints indicate two nodes in the graph and the third represents the edge cost between them

Delfino
  • 967
  • 4
  • 21
  • 46
  • I tested your code on a 2x2 matrix, and it seems to give the correct output. The matrix is `int[][] m = new int[][]{ new int[]{-1, 1}, new int[]{-1, -1} };` – Chthonic Project Jul 26 '15 at 20:20
  • @Delfino: sorry, I've misunderstood your structure. I removed my wrong answer because it was misleading. – Andrea Iacono Jul 28 '15 at 13:10

0 Answers0