Advanced Algorithm Design · Algorithm Design

Floyd-Warshall DP View

Students revisit all-pairs shortest paths as a dynamic programming pattern based on which intermediate vertices are allowed.

Student Focus

This optional page connects two major topics for students preparing for college algorithms.

Guided Lesson Notes

Understanding Floyd-Warshall DP View

Floyd-Warshall DP View focuses on overlapping subproblems, reusable answers, and turning recursion into a table or memo. Students revisit all-pairs shortest paths as a dynamic programming pattern based on which intermediate vertices are allowed.

The mental model is this: define one state as a smaller question whose answer can help build larger answers. That picture matters because it tells the student what information is available immediately and what must be searched, stored, or recomputed.

The core invariant is that when a state is used, every smaller state it depends on must already be correct or memoized. If a solution cannot state that rule, the code may still run on a sample input but fail on edge cases.

A strong implementation usually uses state definitions, recurrence formulas, base cases, table order, memoization maps, and reconstruction when needed. The goal is not just to memorize an API; the goal is to know why each operation is allowed and what it costs.

In competitive programming, Floyd-Warshall DP View tends to appear when the problem asks for best, count, longest, shortest, ways, or choices over prefixes, positions, capacities, or subsets. Spotting that signal is often the difference between a nested-loop solution and an efficient one.

Visual Model

A small picture for Floyd-Warshall DP View

0123012301230123012301230

Key Ideas

  • Intermediate-vertex state
  • Distance matrix updates
  • Graph DP perspective

Practice Prompts

  • Explain the recurrence in words.
  • Compare this DP view with repeated single-source shortest paths.

Vocabulary

Terms students should be able to say clearly

State

A smaller subproblem described by indexes, capacity, mask, or other parameters.

Recurrence

The formula that builds one state from smaller states.

Base case

A state whose answer is known immediately.

Memoization

Top-down caching of recursive answers.

Tabulation

Bottom-up filling of a table.

Transition

One possible move from previous states into the current state.

Worked Example

Worked example: tracing Floyd-Warshall DP View

Use a tiny input and focus on intermediate-vertex state. The goal is to see how the topic changes state before scaling it to a full problem.

  1. 1Write a small input where Floyd-Warshall DP View is clearly useful.
  2. 2Label the part of the input related to Intermediate-vertex state.
  3. 3Perform one operation and explain which invariant is still true afterward.
  4. 4Run a second operation that touches an edge case, such as an empty side, duplicate value, boundary index, disconnected vertex, or tie.
  5. 5Finish by saying which operation dominates the runtime and why.

Complexity Check

Costs students should be able to explain

OperationTypical CostReason
Trace a small inputSmall nUse a tiny example to understand state changes before coding.
Implement the core ideaDepends on topicChoose data structures that match the operations you need.
Analyze growthBig-OExplain how work changes as the input gets larger.

Common Mistakes

What to watch while practicing

  • Coding before drawing the structure or state changes.
  • Forgetting the invariant that makes the algorithm correct.
  • Testing only the sample input and skipping boundary cases.
  • Giving Big-O without explaining which operation dominates the work.

Interview-Style Coding Problem

Floyd-Warshall DP View interview problem: City With Fewest Reachable Neighbors

Interview medium-hard

Problem

Given an undirected weighted graph and a distance threshold, return the city that can reach the fewest other cities within the threshold. Break ties by choosing the larger city index.

Input

The first line contains n, m, and threshold. The next m lines contain edges u v w using 0-based city labels.

Output

Print the chosen city index.

Sample Input

4 4 4
0 1 3
1 2 1
1 3 4
2 3 1

Sample Output

3

Why the sample works

Cities 0 and 3 each reach two cities within distance 4, so the larger index 3 is chosen.

Approach

  1. 1Initialize an all-pairs distance matrix.
  2. 2Run Floyd-Warshall to consider every city as a middle point.
  3. 3Count how many other cities are within the threshold for each city.
  4. 4Update the answer on a smaller count, or on a tie with a larger index.

O(n^3) time and O(n^2) extra space.

Java Solution

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int m = sc.nextInt();
    int threshold = sc.nextInt();

    int inf = 1_000_000_000;
    int[][] dist = new int[n][n];
    for (int i = 0; i < n; i++) {
      Arrays.fill(dist[i], inf);
      dist[i][i] = 0;
    }

    for (int i = 0; i < m; i++) {
      int u = sc.nextInt();
      int v = sc.nextInt();
      int w = sc.nextInt();
      dist[u][v] = Math.min(dist[u][v], w);
      dist[v][u] = Math.min(dist[v][u], w);
    }

    for (int mid = 0; mid < n; mid++) {
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
          if (dist[i][mid] + dist[mid][j] < dist[i][j]) {
            dist[i][j] = dist[i][mid] + dist[mid][j];
          }
        }
      }
    }

    int answer = -1;
    int bestCount = Integer.MAX_VALUE;
    for (int city = 0; city < n; city++) {
      int count = 0;
      for (int other = 0; other < n; other++) {
        if (city != other && dist[city][other] <= threshold) count++;
      }
      if (count <= bestCount) {
        bestCount = count;
        answer = city;
      }
    }

    System.out.println(answer);
  }
}

Python Solution

n, m, threshold = map(int, input().split())
INF = 10 ** 12
dist = [[INF] * n for _ in range(n)]
for i in range(n):
    dist[i][i] = 0

for _ in range(m):
    u, v, w = map(int, input().split())
    dist[u][v] = min(dist[u][v], w)
    dist[v][u] = min(dist[v][u], w)

for mid in range(n):
    for i in range(n):
        for j in range(n):
            if dist[i][mid] + dist[mid][j] < dist[i][j]:
                dist[i][j] = dist[i][mid] + dist[mid][j]

answer = -1
best_count = 10 ** 9
for city in range(n):
    count = sum(1 for other in range(n) if city != other and dist[city][other] <= threshold)
    if count <= best_count:
        best_count = count
        answer = city

print(answer)

Practice Challenge

Make the idea your own

Create a two-minute explanation of Floyd-Warshall DP View: define it, trace one example, name one edge case, and give the runtime of the main operation.

Tutoring Connection

Turn the topic into usable problem-solving skill

Students can use this page before a lesson, after a difficult homework assignment, or while preparing for AP Computer Science A extensions, Advanced Topics in CS, USACO growth, or a college data structures course.