Directed Graph Initialization

随声附和 提交于 2019-12-12 02:38:03

问题


     public class Node {
        private final int vertex;
        private final HashSet<Node> nodes;

        public Node(int index) {
        this.index = index;
        this.nodes = new HashSet<Node>();
       }

       protected void addOutgoingEdge(Node a) {
          nodes.add(a);
        }

       public class DirectedGraph  {
         private Map<Integer, Node> vertices;

       public DirectedGraph(String str) {
         this.vertices = new HashMap<Integer, Node>();
         str = str.replaceAll("[a\\s\\[]", "");
         String[] edges = str.split("]");
           for (String edge : edges) {
            String[] points = edge.split(",");
            int[] integerPoint = new int[2];
            integerPoint[1] = Integer.parseInt(points[1]);
            Node incoming = new Node(integerPoint[0]);
            Node outgoing = new Node(integerPoint[1]);

           // Need to construct the map and add edges here
          }
          }` enter code here`

         protected void addEdge(Node origin, Node destination) {
           origin.addOutgoingEdge(destination);
        }

I am having a bit of some trouble getting the ball rolling on my Directed Graph

I have two classes: A Node class and a DirectedGraph class. The DirectedGraph class will pass in a String to construct a graph. I can't seem to initialize the GraphNode and the respective edges in my DirectedGraph class, however. I know I will be using a Map to get unique keys but the values (outgoing edges) is screwing me up. I know I am very close, I just keep slipping up.

The sample output would be like 1-----> 2 4 -----> 3 5 ------> 4 Where the left column is the vertex and the right column is an outgoing edge. I would appreciate any tips. Here are my classes:


回答1:


Hi I've coded a solution for you I refactored a little your code, and I focused on the relationship creation:

 package com.stackoverflow.graph;

 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;

 /**
  * This class manages the Directed Graph creation, and all the methods related to build a Directed Graph  
  *
  */
 public class DirectedGraph {
     Map<Node, List<Node>> graph;

     public DirectedGraph() {
         this.graph = new HashMap<Node, List<Node>>();
     }

     void createRelationship(Node input, Node output) {
         List<Node> outputs = graph.get(input);
         //If is a new node create their output list, (all the nodes to which it has relationship)
         if (outputs == null)
             outputs = new ArrayList<Node>();
         //Check that the node is not in the list, to avoid duplication
         if (!outputs.contains(output)){
             outputs.add(output);
             graph.put(input,outputs);
         }
     }

     void printGraph(){
         Iterator it = this.graph.entrySet().iterator();
         while (it.hasNext()) {
             Map.Entry pair = (Map.Entry)it.next();
             List<Node> outputs = (List<Node>) pair.getValue();
             for(Node node : outputs){
                 System.out.print(pair.getKey().toString() + "-->" + node + " ");
             }
             it.remove(); // avoids a ConcurrentModificationException
         } 
     }


 }

 ------------------

 package com.stackoverflow.graph;

 public class Node {
     //This is the only field you need for your implementation
     private Integer value;

     public Node(int value){
         this.value = value;
     }


     public Integer getValue() {
         return value;
     }

     public void setValue(Integer value) {
         this.value = value;
     }

     @Override
     public String toString() {
         return value.toString();
     }
 }

 ----------------------

 package com.stackoverflow.graph;

 public class App {

     public static void main(String[] args) {
         DirectedGraph graph = new DirectedGraph();

         //This is the final result, with your parse you must prepare this code to run in this way:
         Node n1 = new Node(1);//Instead of the hardcoded values 1,2,3,4,5 take the parsed ones
         Node n2 = new Node(2);
         Node n3 = new Node(3);
         Node n4 = new Node(4);
         Node n5 = new Node(5);


         //put this code into a loop to create each edge
         graph.createRelationship(n1, n2);
         graph.createRelationship(n3, n4);
         graph.createRelationship(n3, n5);
         //Duplicate relationship but not added
         graph.createRelationship(n3, n5);

         graph.printGraph();
     }
 }

Output:

1-->2 3-->4 3-->5



来源:https://stackoverflow.com/questions/43507283/directed-graph-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!