简体   繁体   English

使用 List 表示包含有向和无向边的图<Integer>

[英]Represent a graph containing directed and undirected edges using List<Integer>

I was asked this question in one of my google interviews.我在一次谷歌面试中被问到这个问题。 I couldn't figure it out.我想不通。 If someone can help that would be great :)如果有人可以提供帮助,那就太好了:)

The class provided was提供的课程是

class Node{
   int data,
   List<Node> outEdges;
}

if you're provided a Node stream containing both directed and undirected edges you have to encode it in such a way that it return List and and decode again to original graph如果您提供了一个包含有向和无向边的 Node 流,您必须对其进行编码,使其返回 List 并再次解码为原始图

List<Integer> encode(Node root){
}

Node decode(List<Integer> graph){
}

The hint provided was you can add your own integers if you want提供的提示是您可以根据需要添加自己的整数

You could just put the data and all the edges in the list and using null as delimiter:您可以将数据和所有边缘放在列表中并使用 null 作为分隔符:

private class IndexAndEdge {
    public Set<Integer> edges = new HashSet<>();
    public int index;
    public int data;
}

List<Integer> encode(Node root) {
    List<Integer> result = new ArrayList<>();
    Map<Node, IndexAndEdge> lookup = new HashMap<>();
    parse(root, lookup);
    result.add(lookup.size());
    lookup.values().stream()
        .sorted((a, b) -> Integer.compare(a.index, b.index))
        .forEach(iae -> {
            result.add(iae.data);
            result.addAll(iae.edges);
            result.add(null);
        });
    result.remove(result.size() - 1);
    return result;
}

private int parse(Node node, Map<Node, IndexAndEdge> lookup) {
    if (lookup.containsKey(node))
        return lookup.get(node).index;
    IndexAndEdge iae = new IndexAndEdge();
    iae.index = lookup.size();
    iae.data = node.data;
    lookup.put(node, iae);
    for (Node n : node.outEdges)
        iae.edges.add(parse(n, lookup));
    return iae.index;
}

Node decode(List<Integer> graph) {
    Node[] nodes = new Node[graph.get(0)];
    for (int i = 0; i < nodes.length; i++) {
        nodes[i] = new Node();
        nodes[i].outEdges = new ArrayList<>();
    }
    int index = 0;
    for (int i = 1; i < graph.size(); i++) {
        Integer n = graph.get(i);
        if (n == null)
            index++;
        else if (nodes[index].outEdges.isEmpty())
            nodes[index].data = n;
        else
            nodes[index].outEdges.add(nodes[n]);
    }
    return nodes[0];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM