如何在 java 中表示图表?

How I can represent a graph in java?

我有这张图

在图表 S 和 P 中取值{1,2,3,4,5}

我想在 java

中表示此图

你能帮我出主意吗?

提前致谢

试试关联矩阵,我认为这是最简单的方法之一。

http://en.wikipedia.org/wiki/Incidence_matrix

您还可以使用以下代码片段使用邻接列表 -

    int n;
    List<Integer>[] adj;
    AdjacencyLists(int n0) {
        n = n0;
        adj = (List<Integer>[])new List[n];
        for (int i = 0; i < n; i++) 
            adj[i] = new ArrayStack<Integer>(Integer.class);
    }  

然后使用函数添加边 -

void addEdge(int i, int j) {
        adj[i].add(j);
    } 

或者可以删除边缘 -

void removeEdge(int i, int j) {
        Iterator<Integer> it = adj[i].iterator();
        while (it.hasNext()) {
            if (it.next() == j) {
                it.remove();
                return;
            }
        }    
    }  

或者甚至检查边是否存在 -

boolean hasEdge(int i, int j) {
        return adj[i].contains(j);
    }  

您可以在此处找到有关 adjacency list 的更多详细信息。

或者您可以使用 adjacency matrix

希望对您有所帮助。
非常感谢