rustpetgraph

How do I make an unweighted, undirected graph with string nodes in Rust?


I would like to create an unweighted, undirected graph with string nodes in Rust. I've been trying to use petgraph and the from_edges construction method provided on UnGraph, but I am unable to do so because &str is not a valid NodeIndex. Is there an easier way to do this?


Solution

  • You can use a HashMap in where the keys are the nodes, and the values are a Vec of nodes connected to the key one. For convenience use String as the primary type for Nodes. Also notice that the graph being undirected just means that you would need to add both nodes to the adjacent list. In the example fashion:

    {
        "start": ["a", "b"],
        "a" : ["b", "d", "end"],
        "b": ["a", "end"],
        "d" : [],
        "end": []
    }
    
    type Graph = HashMap<String, Vec<String>>;
    
    impl Graph {
       ...
    }