HashMap实现邻接列表

问题描述 投票:0回答:1
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中的键数组,但这两个数组不相等。

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

java hashmap
1个回答
2
投票

不要将您的Point存放在array中。将坐标封装在您定义的Point中,并将其存储在HashMap中。 Point有你们观点的坐标成员。别忘了实施equalshashCodefor你的Point

© www.soinside.com 2019 - 2024. All rights reserved.