感谢cyon关于使用广度优先算法的建议,我想出了这个(基于http://java.dzone.com/articles/algorithm-week-graph-breadth):
var graph = {
A : [B, C],
B : [A, D],
C : [A, D],
D : [A, C ,E],
E : [B, F],
F : [E]
};
function init (visited, graph)
{
for (var key in graph) {
var vertex = graph[key];
visited[key] = false;
}
}
function breadthFirst (graph, start, visited)
{
// Create an empty queue
var queue = [];
// Initially enqueue only the starting vertex
queue.push(start);
//Set the starting vertex to visited
visited[start] = true;
//Add it to the result
result.push( start );
//While there is still remaining vertexes in queue
while (queue.length > 0) {
//Remove first vertex from queue and save it in "t"
var currentVertexID = queue.shift();
//For each key in graph at "t"
var currentVertex = graph[currentVertexID];
for (var key in currentVertex) {
var target = currentVertex[key];
//If it has not been visited yet
if (!visited[target]) {
//Mark it as visited
visited[target] = true;
//Add it to queue
queue.push(target);
//Save it in result
result.push(target);
//console.log(result);
}
}
}
}
var result = [];
var visited = [];
init(visited, graph);
breadthFirst(graph, 2, visited);
console.log(result);
而且因为我有一个分离的根,并且在我的图中只有父子关系(因为我是从树迁移而来的),所以我必须在首先使用广度之前建立一个完整的关系矩阵(以便它可以查找父母)。
我发布它是因为它对于预处理很有用,以便在树上首先使用广度
generateNodesAdjacencyMatrix : function(){
var adjacencyMatrix = {};
function recursiveFindNestedAndSaveLinks(parentKey, childrenKeys){
//Add the links to parent pointing to his children
if(!_.isArray(adjacencyMatrix[parentKey])){
adjacencyMatrix[parentKey] = [];
}
adjacencyMatrix[parentKey] = adjacencyMatrix[parentKey].concat(childrenKeys);
//For each children
_.each(childrenKeys, function (childKey){
//Add a link to parent
if(!_.isArray(adjacencyMatrix[childKey])){
adjacencyMatrix[childKey] = [];
}
adjacencyMatrix[childKey].push(parentKey);
//If it has children as well, do recursive on him
var child = childs[childKey];
if(!_.isUndefined(child) && !_.isUndefined(child.children)){
recursiveFindNestedAndSaveLinks(childKey, child.children);
}
}, this);
}
recursiveFindNestedAndSaveLinks('root', root.children);
return adjacencyMatrix;
},