Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions rustworkx-core/src/dag_algo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,10 @@ where
let mut dist: HashMap<G::NodeId, (T, G::NodeId)> = HashMap::with_capacity(nodes.len()); // Stores the distance and the previous node

// Iterate over nodes in topological order
let mut incoming_path: Vec<(T, G::NodeId)> = Vec::new();
for node in nodes {
let parents = graph.edges_directed(node, petgraph::Direction::Incoming);
let mut incoming_path: Vec<(T, G::NodeId)> = Vec::new(); // Stores the distance and the previous node for each parent
incoming_path.clear();
for p_edge in parents {
let p_node = p_edge.source();
let weight: T = weight_fn(p_edge)?;
Expand All @@ -313,8 +314,9 @@ where
}
// Determine the maximum distance and corresponding parent node
let max_path: (T, G::NodeId) = incoming_path
.into_iter()
.iter()
.max_by(|a, b| a.0.partial_cmp(&b.0).unwrap())
.copied()
.unwrap_or((T::zero(), node)); // If there are no incoming edges, the distance is zero

Comment on lines 305 to 321
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't even think you need a Vec at all, no?

Something like

for node in nodes {
    let max_path = graph
        .edges_directed(node, Incoming)
        .try_fold((T::zero(), node), |((max_length, prev), edge)| -> Result<_, E> {
            let source = edge.source();
            let length = dist[&source].0 + weight_fn(edge)?;
            if length > max_length {
                Ok((length, source))
            else {
                Ok((max_length, prev))
            }
        })?;
    // ...

// Store the maximum distance and the corresponding parent node for the current node
Expand Down
Loading