有向图初始化 [英] Directed Graph Initialization

查看:107
本文介绍了有向图初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

     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

我有两个类:Node类和DirectedGraph类。 DirectedGraph类将传入一个String来构造一个图形。但是,我似乎无法初始化GraphNode和DirectedGraph类中的各个边。我知道我将使用Map来获取唯一键,但是值(输出边)使我搞砸了。我知道我已经很近了,我一直在溜溜。

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.

示例输出类似于1 -----> 2 4 -----> 3 5 ------> 4
其中左列是顶点,右列是输出边。我将不胜感激任何提示。这是我的课程:

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:

推荐答案

我为您编码了一个解决方案,我重构了一些代码,我专注于关系创建:

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();
     }
 }

输出:

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

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

这篇关于有向图初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆