ADVANCED DATA STRUCTURES PROGRAM • LEVEL 20 — ADVANCED GRAPH ALGORITHMS

Compute Maximum Flow with Edmonds–Karp

Learn how to compute maximum flow with edmonds–karp using a clear C program.

AdvancedAdvanced graphsGraph optimization

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Maximum flow = 23

COMPLETE C PROGRAM

Complete C implementation

ads-edmonds-karp-max-flow.c
Open in compiler
#include <stdio.h>

int max_flow(int capacity[6][6],int source,int sink){int flow=0,parent[6],queue[6];for(;;){for(int i=0;i<6;i++)parent[i]=-1;int front=0,back=0;queue[back++]=source;parent[source]=source;while(front<back&&parent[sink]<0){int node=queue[front++];for(int next=0;next<6;next++)if(parent[next]<0&&capacity[node][next]>0){parent[next]=node;queue[back++]=next;}}if(parent[sink]<0)break;int add=1000000;for(int v=sink;v!=source;v=parent[v])if(capacity[parent[v]][v]<add)add=capacity[parent[v]][v];for(int v=sink;v!=source;v=parent[v]){capacity[parent[v]][v]-=add;capacity[v][parent[v]]+=add;}flow+=add;}return flow;}

int main(void)
{
    int capacity[6][6]={{0,16,13,0,0,0},{0,0,10,12,0,0},{0,4,0,0,14,0},{0,0,9,0,0,20},{0,0,0,7,0,4},{0,0,0,0,0,0}};printf("Maximum flow = %d\n",max_flow(capacity,0,5));return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Maximum flow = 23
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Use BFS to choose the shortest residual augmenting path until no path reaches the sink.
  3. Display the computed result.

Use BFS to choose the shortest residual augmenting path until no path reaches the sink.

EFFICIENCY

Time and space complexity

Time complexity

O(VE^2)

Auxiliary space

O(V + E)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.