着色图如果我有 Map<T,List<T>> 图形结构

问题描述

所以我很难找到给图表着色的逻辑。

这是我的代码

import java.util.*;

class Graph<T> {

    // We use Hashmap to store the edges in the graph
    private final Map<T,List<T> > map = new HashMap<>();

    // This function adds a new vertex to the graph
    public void addVertex(T s)
    {
        map.put(s,new LinkedList<>());
    }

    // This function adds the edge
    // between source to destination
    public void addEdge(T source,T destination,boolean bidirectional)
    {

        if (!map.containsKey(source))
            addVertex(source);

        if (!map.containsKey(destination))
            addVertex(destination);

        map.get(source).add(destination);
        if (bidirectional) {
            map.get(destination).add(source);
        }
    }

    // This function gives the count of vertices
    public void getVertexCount()
    {
        System.out.println("The graph has "
                + map.keySet().size()
                + " vertex");
    }

    // This function gives the count of edges
    public void getEdgesCount(boolean bidirection)
    {
        int count = 0;
        for (T v : map.keySet()) {
            count += map.get(v).size();
        }
        if (bidirection) {
            count = count / 2;
        }
        System.out.println("The graph has "
                + count
                + " edges.");
    }
@Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();


        for (T v : map.keySet()) {
            builder.append(v.toString()).append(": { ");
            for (T w : map.get(v)) {
                builder.append(w.toString()).append(" ");
            }
            builder.append("}\n");
        }

        return (builder.toString());
    }

我有这样的主要方法

public static void main(String args[]) {

        // Object of graph is created.
        Graph<String> g = new Graph<String>();

        // edges are added.
        // Since the graph is bidirectional,// so boolean bidirectional is passed as true.
        g.addEdge("B","A",true);
        g.addEdge("B","C",true);
        g.addEdge("A","D","G",true);
        g.addEdge("C",true);
        g.addEdge("D","E",true);
        g.addEdge("G",true);
        g.addEdge("F","F",true);

然后输出:

Graph:
A: { B D G }
B: { A C }
C: { B D }
D: { A C E }
E: { D G F }
F: { E G }
G: { A E F }

但我想为每个节点赋予颜色,我想要类似的东西

A = { 1 }
B = { 2 }
C = { 1 }
D = { 3 }
E = { 1 }
F = { 2 }
G = { 4 }

但我不知道在我的图表中实现一些算法。我在一些网站上冲浪,但他们只是使用 2D 列表或数组列表创建示例。在这种情况下,我的图中有 Map >。

请我需要你的帮助

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...