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 int
s indicate two nodes in the graph and the third represents the edge cost between them