Finding All Connected Components of an Undirected Graph

前端 未结 3 1694
栀梦
栀梦 2020-12-29 15:48

I have a list of objects (undirected edges) like below:

pairs = [

 pair:[\"a2\", \"a5\"],
 pair:[\"a3\", \"a6\"],
 pair:[\"a4\", \"a5\"],
 pair:[\"a7\", \"a         


        
3条回答
  •  执笔经年
    2020-12-29 16:11

    You want to do Graph Traversal

    In your specific example, you have no # of nodes, and it may even be difficult to traverse the graph so first we'll get a "graph"

    // It will return an object like Vertices{node: EdgesTo{node,node}, node:...}
    function toGraph(arr) {
        var graph = {}; // this will hold the node "IDs"
        for (var i = 0; i < arr.length; i++) {
            // "create node" if the it's not added in the graph yet
            graph[arr[i][0]] = graph[arr[i][0]] || {};
            graph[arr[i][1]] = graph[arr[i][1]] || {};
            // add bidirectional "edges" to the "vertices"
            // Yes, we set the value to null, but what's important is to add the key.
            graph[arr[i][0]][arr[i][1]] = null;
            graph[arr[i][1]][arr[i][0]] = null;
        }
        return graph;
    }
    

    Then it is very easy to traverse the graph using any method that you choose (DFS, BFS)

    I will make an example using DFS:

    // to be called after getting the result from toGraph(arr)
    function getSubGraphs(graph) {
        var subGraphs = []; // array of connected vertices
        var visited = {};
        for (var i in graph) { // for every node...
            var subGraph = dfs(graph, i, visited); // ... we call dfs
            if (subGraph != null) // if vertex is not added yet in another graph
            subGraphs.push(subGraph);
        }
        return subGraphs;
    }
    
    // it will return an array of all connected nodes in a subgraph
    function dfs(graph, node, visited) {
        if (visited[node]) return null; // node is already visited, get out of here.
        var subGraph = [];
        visited[node] = true;
        subGraph.push(node);
        for (var i in graph[node]) {
            var result = dfs(graph, i, visited);
            if (result == null) continue;
            subGraph = subGraph.concat(result);
        }
        return subGraph;
    }
    

    And you would end up calling it like getSubGraphs(toGraph(myArray)); and do whatever you need with that.

    Fiddle Here

提交回复
热议问题