I'm writing a class in Java to represent a Graph data structure. This is specific to an undirected, unweighted graph and it's purpose is mainly for edge testing (is node A connected to node B, either directly or indirectly).
I need help implementing the indirectEdgeTest method. In the code below, I've only commented this method and I'm returning false so the code will compile as-is.
I have put some time into coming up with an algorithm, but I can't seem to find anything more simple than this, and I fear I'm making it more complicated than it needs to be:
- test first for a direct connection
- if no direct connection exists from node a to node b:
- for every edge i connected to node a:
- create a new graph that does not contain edge a -> i
- test new graph for indirect connectivity between nodes i and b
Either pseudocode or actual Java code is welcome in your answers. Thanks for your help. Here's the code I have:
class Graph {
// This is for an undirected, unweighted graph
// This implementation uses an adjacency matrix for speed in edge testing
private boolean[][] edge;
private int numberOfNodes;
public Graph(int numNodes) {
// The indices of the matrix will not be zero-based, for clarity,
// so the size of the array will be increased by 1.
edge = new boolean[numNodes + 1][numNodes + 1];
numberOfNodes = numNodes;
}
public void addEdge(int a, int b) {
if (a <= numberOfNodes && a >= 1) {
if (b <= numberOfNodes && b >= 1) {
edge[a][b] = true;
edge[b][a] = true;
}
}
}
public void removeEdge(int a, int b) {
if (a <= numberOfNodes && a >= 1) {
if (b <= numberOfNodes && b >= 1) {
edge[a][b] = false;
edge[b][a] = false;
}
}
}
public boolean directEdgeTest(int a, int b) {
// if node a and node b are directly connected, return true
boolean result = false;
if (a <= numberOfNodes && a >= 1) {
if (b <= numberOfNodes && b >= 1) {
if (edge[a][b] == true) {
result = true;
}
}
}
return result;
}
public boolean indirectEdgeTest(int a, int b) {
// if there exists a path from node a to node b, return true
// implement indirectEdgeTest algorithm here.
return false;
}
}