Warshall-Floyd
(graph/warshall_floyd.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/warshall_floyd.hpp"
Overview
Warshall-Floyd computes shortest paths between every pair of vertices. It keeps
a distance matrix and tries each vertex k as an intermediate point, improving
dist[i][j] with dist[i][k] + dist[k][j].
Use it when N is small enough for $O(N^3)$ time and you need many shortest
path queries after preprocessing. It can handle negative edge costs, but if a
negative cycle exists, shortest distances involving that cycle are not
well-defined.
For one-source shortest paths on larger graphs, use Dijkstra or Bellman-Ford.
Graph Orientation
Direction is respected. warshall_floyd works on directed graphs as written,
and also on undirected graphs built with add_edge.
How to Use It
There are two entry points:
-
warshall_floyd(g)builds the initial matrix from aGraph<T>. -
warshall_floyd(dist)starts from a matrix you prepared yourself and runs the full $O(N^3)$ Floyd-Warshall transition on it.
For a custom matrix, initialize dist[i][i] = 0, unreachable entries to inf,
and direct edge costs to their minimum values.
This second overload is useful when your initial distances do not come directly
from Graph<T>, for example when you already have a dense matrix or want to
set some distances manually before running all-pairs shortest paths.
After running the algorithm, dist[s][t] is the shortest distance from s to
t, or inf if t is unreachable from s.
Use has_negative_cycle(dist) after the relaxation. It checks whether some
dist[i][i] became negative.
Adding an Edge
After computing an all-pairs distance matrix, adding one edge can be applied in $O(N^2)$.
The input matrix must already be the correct all-pairs shortest distance matrix for the graph before adding the edge.
For a new directed edge from -> to with cost cost, every improved shortest
path has the form:
i -> ... -> from -> to -> ... -> j
So the function checks:
dist[i][j] = min(dist[i][j], dist[i][from] + cost + dist[to][j])
Use warshall_floyd_add_directed_edge(dist, from, to, cost) for a directed
edge and warshall_floyd_add_undirected_edge(dist, u, v, cost) for an
undirected edge. Adding a parallel edge with a smaller cost is the same
operation.
These functions modify dist in place and return true if at least one entry
changed.
Functions
| Function | Signature | Description | Complexity |
|---|---|---|---|
warshall_floyd |
template <class T> std::vector<std::vector<T>> warshall_floyd(const Graph<T>& g, T inf = std::numeric_limits<T>::max() / T(4)) |
Builds and relaxes the distance matrix from a graph. | $O(N^3)$ |
warshall_floyd |
template <class T> std::vector<std::vector<T>> warshall_floyd(std::vector<std::vector<T>> dist, T inf = std::numeric_limits<T>::max() / T(4)) |
Runs the full Floyd-Warshall transition on a matrix you initialized yourself. | $O(N^3)$ |
warshall_floyd_add_directed_edge |
template <class T> bool warshall_floyd_add_directed_edge(std::vector<std::vector<T>>& dist, int from, int to, T cost, T inf = std::numeric_limits<T>::max() / T(4)) |
Adds one directed edge to an already-computed distance matrix. | $O(N^2)$ |
warshall_floyd_add_undirected_edge |
template <class T> bool warshall_floyd_add_undirected_edge(std::vector<std::vector<T>>& dist, int u, int v, T cost, T inf = std::numeric_limits<T>::max() / T(4)) |
Adds one undirected edge to an already-computed distance matrix. | $O(N^2)$ |
has_negative_cycle |
template <class T> bool has_negative_cycle(const std::vector<std::vector<T>>& dist) |
Checks whether any diagonal entry is negative. | $O(N)$ |
Example
#include "graph/graph.hpp"
#include "graph/warshall_floyd.hpp"
#include <iostream>
int main() {
m1une::graph::Graph<long long> g(3);
g.add_directed_edge(0, 1, 5);
g.add_directed_edge(1, 2, 7);
g.add_directed_edge(0, 2, 20);
auto dist = m1une::graph::warshall_floyd(g);
std::cout << dist[0][2] << "\n"; // 12
m1une::graph::warshall_floyd_add_directed_edge(dist, 0, 2, 4LL);
std::cout << dist[0][2] << "\n"; // 4
}
Depends on
Required by
Graph All
(graph/all.hpp)
Directed Graph Algorithms
(graph/directed.hpp)
Shortest Path
(graph/shortest_path.hpp)
Undirected Graph Algorithms
(graph/undirected.hpp)
Verified with
verify/graph/cow_game.test.cpp
verify/graph/graph_algorithms.test.cpp
verify/graph/range_edge_graph.test.cpp
Code
#ifndef M1UNE_GRAPH_WARSHALL_FLOYD_HPP
#define M1UNE_GRAPH_WARSHALL_FLOYD_HPP 1
#include <cassert>
#include <limits>
#include <utility>
#include <vector>
#include "graph.hpp"
namespace m1une {
namespace graph {
template <class T>
std::vector<std::vector<T>> warshall_floyd(std::vector<std::vector<T>> dist,
T inf = std::numeric_limits<T>::max() / T(4)) {
int n = int(dist.size());
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
if (dist[i][k] == inf) continue;
for (int j = 0; j < n; j++) {
if (dist[k][j] == inf) continue;
T nd = dist[i][k] + dist[k][j];
if (nd < dist[i][j]) dist[i][j] = nd;
}
}
}
return dist;
}
template <class T>
std::vector<std::vector<T>> warshall_floyd(const Graph<T>& g, T inf = std::numeric_limits<T>::max() / T(4)) {
int n = g.size();
std::vector<std::vector<T>> dist(n, std::vector<T>(n, inf));
for (int i = 0; i < n; i++) dist[i][i] = T(0);
for (int v = 0; v < n; v++) {
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (e.cost < dist[e.from][e.to]) dist[e.from][e.to] = e.cost;
}
}
return warshall_floyd(std::move(dist), inf);
}
template <class T>
bool warshall_floyd_add_directed_edge(std::vector<std::vector<T>>& dist, int from, int to, T cost,
T inf = std::numeric_limits<T>::max() / T(4)) {
int n = int(dist.size());
assert(0 <= from && from < n);
assert(0 <= to && to < n);
std::vector<T> to_from(n), from_to(n);
for (int i = 0; i < n; i++) {
to_from[i] = dist[i][from];
from_to[i] = dist[to][i];
}
bool updated = false;
for (int i = 0; i < n; i++) {
if (to_from[i] == inf) continue;
for (int j = 0; j < n; j++) {
if (from_to[j] == inf) continue;
T nd = to_from[i] + cost + from_to[j];
if (nd < dist[i][j]) {
dist[i][j] = nd;
updated = true;
}
}
}
return updated;
}
template <class T>
bool warshall_floyd_add_undirected_edge(std::vector<std::vector<T>>& dist, int u, int v, T cost,
T inf = std::numeric_limits<T>::max() / T(4)) {
int n = int(dist.size());
assert(0 <= u && u < n);
assert(0 <= v && v < n);
std::vector<T> to_u(n), from_u(n), to_v(n), from_v(n);
for (int i = 0; i < n; i++) {
to_u[i] = dist[i][u];
from_u[i] = dist[u][i];
to_v[i] = dist[i][v];
from_v[i] = dist[v][i];
}
bool updated = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (to_u[i] != inf && from_v[j] != inf) {
T nd = to_u[i] + cost + from_v[j];
if (nd < dist[i][j]) {
dist[i][j] = nd;
updated = true;
}
}
if (to_v[i] != inf && from_u[j] != inf) {
T nd = to_v[i] + cost + from_u[j];
if (nd < dist[i][j]) {
dist[i][j] = nd;
updated = true;
}
}
}
}
return updated;
}
template <class T>
bool has_negative_cycle(const std::vector<std::vector<T>>& dist) {
int n = int(dist.size());
for (int i = 0; i < n; i++) {
if (dist[i][i] < T(0)) return true;
}
return false;
}
} // namespace graph
} // namespace m1une
#endif // M1UNE_GRAPH_WARSHALL_FLOYD_HPP#line 1 "graph/warshall_floyd.hpp"
#include <cassert>
#include <limits>
#include <utility>
#include <vector>
#line 1 "graph/graph.hpp"
#include <array>
#line 8 "graph/graph.hpp"
namespace m1une {
namespace graph {
template <class T = int>
struct Edge {
using cost_type = T;
int from;
int to;
T cost;
int id;
bool alive;
Edge() : from(-1), to(-1), cost(T()), id(-1), alive(true) {}
Edge(int from_, int to_, T cost_ = T(1), int id_ = -1, bool alive_ = true)
: from(from_), to(to_), cost(cost_), id(id_), alive(alive_) {}
int other(int v) const {
assert(v == from || v == to);
return from ^ to ^ v;
}
};
template <class T = int>
struct Graph {
using edge_type = Edge<T>;
using cost_type = T;
private:
struct EdgePositions {
std::array<std::pair<int, int>, 2> value{};
int size = 0;
void push_back(std::pair<int, int> position) {
assert(size < 2);
value[size++] = position;
}
};
int _n;
int _edge_count;
std::vector<std::vector<edge_type>> _g;
std::vector<EdgePositions> _edge_positions;
public:
Graph() : _n(0), _edge_count(0) {}
explicit Graph(int n) : _n(n), _edge_count(0), _g(n) {
assert(0 <= n);
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int edge_count() const {
return _edge_count;
}
int add_vertex() {
_g.emplace_back();
return _n++;
}
int add_directed_edge(int from, int to, T cost = T(1)) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int id = _edge_count++;
int idx = int(_g[from].size());
_g[from].push_back(edge_type(from, to, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({from, idx});
return id;
}
int add_edge(int u, int v, T cost = T(1)) {
assert(0 <= u && u < _n);
assert(0 <= v && v < _n);
int id = _edge_count++;
int u_idx = int(_g[u].size());
_g[u].push_back(edge_type(u, v, cost, id));
int v_idx = int(_g[v].size());
_g[v].push_back(edge_type(v, u, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({u, u_idx});
_edge_positions.back().push_back({v, v_idx});
return id;
}
void set_edge_alive(int id, bool alive) {
assert(0 <= id && id < _edge_count);
for (int i = 0; i < _edge_positions[id].size; ++i) {
auto [v, idx] = _edge_positions[id].value[i];
_g[v][idx].alive = alive;
}
}
void erase_edge(int id) {
set_edge_alive(id, false);
}
void revive_edge(int id) {
set_edge_alive(id, true);
}
bool is_edge_alive(int id) const {
assert(0 <= id && id < _edge_count);
assert(_edge_positions[id].size != 0);
auto [v, idx] = _edge_positions[id].value[0];
return _g[v][idx].alive;
}
const std::vector<edge_type>& operator[](int v) const {
assert(0 <= v && v < _n);
return _g[v];
}
std::vector<edge_type>& operator[](int v) {
assert(0 <= v && v < _n);
return _g[v];
}
const std::vector<std::vector<edge_type>>& adjacency() const {
return _g;
}
std::vector<std::vector<edge_type>>& adjacency() {
return _g;
}
std::vector<edge_type> edges(bool include_inactive = false) const {
std::vector<edge_type> result;
result.reserve(_edge_count);
std::vector<char> used(_edge_count, false);
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
if (!include_inactive && !e.alive) continue;
if (0 <= e.id && e.id < _edge_count) {
if (used[e.id]) continue;
used[e.id] = true;
}
result.push_back(e);
}
}
return result;
}
Graph reversed() const {
Graph result(_n);
result._edge_count = _edge_count;
result._edge_positions.assign(_edge_count, {});
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
int idx = int(result._g[e.to].size());
result._g[e.to].push_back(edge_type(e.to, e.from, e.cost, e.id, e.alive));
if (0 <= e.id && e.id < _edge_count) result._edge_positions[e.id].push_back({e.to, idx});
}
}
return result;
}
};
} // namespace graph
} // namespace m1une
#line 10 "graph/warshall_floyd.hpp"
namespace m1une {
namespace graph {
template <class T>
std::vector<std::vector<T>> warshall_floyd(std::vector<std::vector<T>> dist,
T inf = std::numeric_limits<T>::max() / T(4)) {
int n = int(dist.size());
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
if (dist[i][k] == inf) continue;
for (int j = 0; j < n; j++) {
if (dist[k][j] == inf) continue;
T nd = dist[i][k] + dist[k][j];
if (nd < dist[i][j]) dist[i][j] = nd;
}
}
}
return dist;
}
template <class T>
std::vector<std::vector<T>> warshall_floyd(const Graph<T>& g, T inf = std::numeric_limits<T>::max() / T(4)) {
int n = g.size();
std::vector<std::vector<T>> dist(n, std::vector<T>(n, inf));
for (int i = 0; i < n; i++) dist[i][i] = T(0);
for (int v = 0; v < n; v++) {
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (e.cost < dist[e.from][e.to]) dist[e.from][e.to] = e.cost;
}
}
return warshall_floyd(std::move(dist), inf);
}
template <class T>
bool warshall_floyd_add_directed_edge(std::vector<std::vector<T>>& dist, int from, int to, T cost,
T inf = std::numeric_limits<T>::max() / T(4)) {
int n = int(dist.size());
assert(0 <= from && from < n);
assert(0 <= to && to < n);
std::vector<T> to_from(n), from_to(n);
for (int i = 0; i < n; i++) {
to_from[i] = dist[i][from];
from_to[i] = dist[to][i];
}
bool updated = false;
for (int i = 0; i < n; i++) {
if (to_from[i] == inf) continue;
for (int j = 0; j < n; j++) {
if (from_to[j] == inf) continue;
T nd = to_from[i] + cost + from_to[j];
if (nd < dist[i][j]) {
dist[i][j] = nd;
updated = true;
}
}
}
return updated;
}
template <class T>
bool warshall_floyd_add_undirected_edge(std::vector<std::vector<T>>& dist, int u, int v, T cost,
T inf = std::numeric_limits<T>::max() / T(4)) {
int n = int(dist.size());
assert(0 <= u && u < n);
assert(0 <= v && v < n);
std::vector<T> to_u(n), from_u(n), to_v(n), from_v(n);
for (int i = 0; i < n; i++) {
to_u[i] = dist[i][u];
from_u[i] = dist[u][i];
to_v[i] = dist[i][v];
from_v[i] = dist[v][i];
}
bool updated = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (to_u[i] != inf && from_v[j] != inf) {
T nd = to_u[i] + cost + from_v[j];
if (nd < dist[i][j]) {
dist[i][j] = nd;
updated = true;
}
}
if (to_v[i] != inf && from_u[j] != inf) {
T nd = to_v[i] + cost + from_u[j];
if (nd < dist[i][j]) {
dist[i][j] = nd;
updated = true;
}
}
}
}
return updated;
}
template <class T>
bool has_negative_cycle(const std::vector<std::vector<T>>& dist) {
int n = int(dist.size());
for (int i = 0; i < n; i++) {
if (dist[i][i] < T(0)) return true;
}
return false;
}
} // namespace graph
} // namespace m1une