使用HashMap实现图表

时间:2016-01-07 20:03:32

标签: java graph

我是Java的新手,所以在触发快乐向下投票之前请记住这一点。我熟悉使用数组的整数图的流行实现。

Graph{
 int vertices;
 LinkedList<Integer>[] adj;

Graph(int vertices){
   this.vertices = vertices;
   adj = new LinkedList<>();
   for(int i= 0; i <vertices; i++){
      adj[i] = new LinkedList(); 
   }
}

但是,此实现最适合整数图。 如果我想要字符的implmentation图,这个实现不会使自己直接使用。 所以我尝试使用HashMap实现。

public class Graph {
    int vertices;
    HashMap<Character, LinkedList<Character>> adj;


    Graph(int item){

       this.vertices = item;
       adj = new HashMap<>();

    }
}

我在语法上与Java有点混淆,就是在这个HashTable中添加键和值。我试图做的是实现这种方法。

public void add(Character a, Character b){

            if (adj.containsKey(a)){

               //get a reference to the existing linked list
               //add to the existing LinkedList
            }else{

               //create a new LinkedList and add to it.
            }

        }
    }

我可以使用不完整的add方法的一些帮助,以及在构造图形之后如何遍历this adj HashMap。

2 个答案:

答案 0 :(得分:2)

由于您的问题仅与语法有关,因此您可以执行以下操作:

<html>  
<head>

  <title>Template me</title>
  
  <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.0.1/lib/polymer/polymer.html">  

  
</head>
<body class="fullbleed">

<template-me></template-me>

<dom-module id="template-me">
  <template>
   <style>
        div { color: red }
        </style>
        <div>This is local DOM</div>
    

  </template>
              
  <script>
    Polymer({
      is : "template-me"
      });
    </script>
    
</dom-module>

</body>
</html>

答案 1 :(得分:0)

HashMap将节点编号存储为密钥,将所有相邻节点的列表存储为值。该列表已使用LinkedList class实施。只需根据您的要求更改Key类和值。

class Graph{
HashMap<Integer,LinkedList<Integer>> map = new HashMap<>();

//add an edge from source to destination
void addEdge(int src, int dest){
    if(!map.containsKey(src)){
        LinkedList<Integer> l= new LinkedList<>();
        l.add(dest);
        map.put(src,l);
    }

    else{
        LinkedList<Integer> l= map.get(src);
        l.add(dest);
        map.put(src,l);
    }
}

//display the adjency list
void displayGraph(){
    for(Map.Entry m: map.entrySet()){
        System.out.println(m.getKey()+"-->"+m.getValue());
    }
}
public static void main(String[] args) {

    Graph g= new Graph();
    g.addEdge(0,1);
    g.addEdge(0,4);
    g.addEdge(0,5);
    g.addEdge(1,4);
    g.addEdge(1,3);
    g.addEdge(3,2);
    g.addEdge(2,1);
    g.addEdge(3,4);
    g.displayGraph();
}
}

输出:

  0-->[1, 4, 5]
  1-->[4, 3]
  2-->[1]
  3-->[2, 4]
相关问题