HashMap实现邻接列表

时间:2016-08-12 17:12:59

标签: java hashmap

class Graph {
//Map of adjacency lists for each node

    Map<int[], LinkedList<int[]>> adj;

    public Graph(ArrayList<int[]> nodes) {
        adj = new HashMap<int[], LinkedList<int[]>>();
        for (int i = 0; i < nodes.size(); ++i) {
            adj.put(nodes.get(i), new LinkedList<int[]>());
        }
    }

    public void addNeighbor(int [] a, int [] b) {
        adj.get(a).add(b);
    } 

    public LinkedList<int[]> getNeighbors(int a[]) {
        return adj.get(a);
    }
}


public class Assignment2 {

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int x= sc.nextInt();
        int y= sc.nextInt();
        int n= sc.nextInt();

        ArrayList<int []> al= new ArrayList<>();
        for(int i=0;i<n;i++){
            int[] a = new int[2];
            a[0]=sc.nextInt();
            a[1]=sc.nextInt();
            al.add(i, a);
        }
        int[] s={0,100};
        int[] t={x-5,150};
        Graph g = new Graph(al);
        g.adj.put(s, new LinkedList<int[]>());
        g.adj.put(t, new LinkedList<int[]>());
        for(int i=0;i<al.size();i++){
            int a[]=al.get(i);
            for(int j=i;j<al.size();j++){
                int b[]=al.get(j);
                int r=100;
                int value=(int) (Math.pow(a[0]-b[0],2)+Math.pow(a[1]-b[1],2));
                if(0<=value && value <=200){
                g.addNeighbor(a, b);
                g.addNeighbor(b, a);
            }   
        }
    }
}

我必须实现一个邻接列表,用于我使用HashMap的图,因为你可以看到键值是一个包含坐标值(x,y)的数组,它代表图中的一个顶点。

问题是当我想在图中添加一个新邻居时,即在两个顶点之间添加一条边,我需要将该邻居添加到相应的键,但该键是一个数组...所以我想知道怎么做我访问密钥或添加到该密钥的邻居。我所做的是创建了一个新数组,其值等于存储在hashmap中的键数组,但这两个数组不相等。

请提供解决方案或任何其他方式来存储坐标

1 个答案:

答案 0 :(得分:2)

请勿将您的Point存储在array中。将坐标封装在您定义的Point中,并将其存储在HashMap中。 Point有您所关注坐标的成员。不要忘记为equals实施hashCodePoint