Skip to content

Commit

Permalink
Added from_graph function for graphmap
Browse files Browse the repository at this point in the history
  • Loading branch information
Indeximal committed Jun 7, 2022
1 parent bd6aea4 commit 00ab85b
Showing 1 changed file with 32 additions and 16 deletions.
48 changes: 32 additions & 16 deletions src/graphmap.rs
Expand Up @@ -154,22 +154,7 @@ where
D: serde::Deserializer<'de>,
{
let equivalent_graph: Graph<N, E, Ty, u32> = Graph::deserialize(deserializer)?;
let mut graph: GraphMap<N, E, Ty> =
GraphMap::with_capacity(equivalent_graph.node_count(), equivalent_graph.edge_count());

for node in equivalent_graph.raw_nodes() {
graph.add_node(node.weight);
}

for edge in equivalent_graph.edge_indices() {
let (a, b) = equivalent_graph.edge_endpoints(edge).unwrap();
graph.add_edge(
*equivalent_graph.node_weight(a).unwrap(),
*equivalent_graph.node_weight(b).unwrap(),
equivalent_graph.edge_weight(edge).unwrap().clone(),
);
}
Ok(graph)
Ok(GraphMap::from_graph(equivalent_graph))
}
}

Expand Down Expand Up @@ -534,6 +519,37 @@ where
}
gr
}

/// Creates a `GraphMap` that corresponds to the given `Graph`.
///
/// Note that node and edge indices in the `Graph` are lost in this process,
/// but the weights are kept.
/// **Warning**: Parallel edges are lost, only the last one remains.
///
/// Computes in **O(|V| + |E|)** time (average).
pub fn from_graph<Ix>(graph: Graph<N, E, Ty, Ix>) -> Self
where
Ix: crate::graph::IndexType,
E: Clone,
{
let mut new_graph: GraphMap<N, E, Ty> =
GraphMap::with_capacity(graph.node_count(), graph.edge_count());

for node in graph.raw_nodes() {
new_graph.add_node(node.weight);
}

for edge in graph.edge_indices() {
let (a, b) = graph.edge_endpoints(edge).unwrap();
new_graph.add_edge(
*graph.node_weight(a).unwrap(),
*graph.node_weight(b).unwrap(),
graph.edge_weight(edge).unwrap().clone(),
);
}

new_graph
}
}

/// Create a new `GraphMap` from an iterable of edges.
Expand Down

0 comments on commit 00ab85b

Please sign in to comment.