我需要测试哪个顶点是“重要的”,当连接边缘被移除时,图形会断开连接。所以我的想法是尝试删除每个边缘,然后测试从1节点到另一个节点的连接。
示例:删除连接2 - 5的边缘。然后测试2 - 5的连接:isConnected(2,5)
// DFS from node1 to node2
boolean isConnected(int node1, int node2) {
// keep track of (visited) status of nodes
visited = new VertexState[V];
for (int i = 0; i < V; i++)
visited[i] = VertexState.NotVisited;
// recursively test connectivity
return _isConnected(node1, node2);
}
boolean _isConnected(int node1, int node2) {
visited[node1] = VertexState.Visiting;
if (node1 == node2) { // we found the node
return true;
} else {
for (int i = 0; i < V; i++) { // for all children of node1
if (AdjMatrix[node1][i] == 1 && visited[i] == VertexState.NotVisited) {
if (_isConnected(i, node2)) { // test if child can reach node2
return true;
}
}
}
visited[node1] = VertexState.Visited;
}
return false;
}
当我尝试使用简单的图表时,它可以正常工作,但是当我使用复杂的测试用例进行测试时,它似乎会产生错误的结果。我调试很困难,因为它是一个复杂的测试用例,无法将其绘制出来。
更新
如果它只对伪代码有帮助:
isConnected(node1, node2)
visited = new VertexState[V]
for each v in visited
v = NotVisited
return _isConnected(node1, node2); // the recursion
_isConnected(node1, node2)
visited[node1] = Visiting
if (node1 == node2)
return true // we found the node
else
for each neighbour of node1
if visited[neighbour] == NotVisited
if_isConnected(neighbour, node2)
return true
visited[node1] = Visited
return false
更新2
完整的来源 https://gist.github.com/3779445 ,但是使用邻接列表,它似乎可行...不确定它是否是最有效的算法......