グラフのデータ構造を表すクラスをJavaで書いています。これは、無向、無加重グラフに固有であり、その目的は主にエッジテスト(ノードAがノードBに直接または間接的に接続されている)を目的としています。
indirectEdgeTestメソッドの実装についてサポートが必要です。以下のコードでは、このメソッドにコメントを付けただけで、falseを返しているので、コードはそのままコンパイルされます。
アルゴリズムを考え出すのに少し時間をかけましたが、これよりも単純なものは見つからないようです。必要以上に複雑になっているのではないかと心配しています。
- 最初に直接接続をテストします
- ノードaからノードbへの直接接続が存在しない場合:
- ノードaに接続されているすべてのエッジについて:
- エッジa->iを含まない新しいグラフを作成します
- ノードiとbの間の間接接続について新しいグラフをテストします
- ノードaに接続されているすべてのエッジについて:
擬似コードまたは実際のJavaコードのいずれかがあなたの答えに歓迎されます。これが私が持っているコードです:
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;
}
}