Class FloydWarshall

Inheritance Relationships

Base Type

Class Documentation

class FloydWarshall : public NetworKit::Algorithm

Computes all-pairs shortest paths using the Floyd-Warshall algorithm.

This algorithm finds the shortest paths between all node pairs in a weighted graph, supporting both directed and undirected graphs. It correctly handles negative edge weights and detects negative cycles. If multiple shortest paths exist, it returns one with the fewest nodes.

The algorithm has a time complexity of O(n³), making it suitable for small to medium-sized graphs.

Public Functions

FloydWarshall(const Graph &G)

Initializes the Floyd-Warshall algorithm for a given graph.

The input graph must be weighted and may be either directed or undirected.

Parameters:

G – The graph on which shortest paths will be computed.

virtual void run() override

Runs the Floyd-Warshall algorithm.

Computes shortest path distances and reconstructs paths between all node pairs. Also identifies nodes involved in negative cycles.

edgeweight getDistance(node source, node target) const

Returns the shortest distance between two nodes.

If no path exists, returns std::numeric_limits<edgeweight>::max().

Parameters:
  • source – The starting node.

  • target – The destination node.

Returns:

The shortest path distance from source to target.

bool isNodeInNegativeCycle(node u) const

Checks whether a node is part of a negative cycle.

A node is considered part of a negative cycle if its shortest path distance to itself is negative.

Parameters:

u – The node to check.

Returns:

true if the node is in a negative cycle, otherwise false.

std::vector<node> getNodesOnShortestPath(node source, node target) const

Retrieves the shortest path between two nodes.

Returns a sequence of nodes representing the shortest path from source to target. If no path exists, returns an empty vector.

If multiple shortest paths exist with the same total distance, the function returns the one with the fewest nodes.

Parameters:
  • source – The starting node.

  • target – The destination node.

Returns:

A vector of nodes forming the shortest path.