Find the Maximum Flow | Practice | GeeksforGeeks

Given a graph which represents a flow network with N vertices numbered 1 to N and M edges.Find the maximum flow from vertex numbered 1 to vertex numbered N.
In a flow network,every edge has a flow capacity and the maximum flow of a path can't exceed the flow-capacity of an edge in the path.

Example 1:
Input:
N = 5, M =  4
Edges[]= {{1,2,1},{3,2,2},{4,2,3},{2,5,5}}
Output: 1 
Explanation: 
1 - 2 - 3
   / \
  4   5 
1 unit can flow from 1 -> 2 - >5 

 
Example 2:
Input:
N = 4, M = 4
Edges[] = {{1,2,8},{1,3,10},{4,2,2},{3,4,3}}
Output: 5 
Explanation:
  1 - 2 
  |   |
  3 - 4
3 unit can flow from 1 -> 3 -> 4
2 unit can flow from 1 -> 2 -> 4
Total max flow from 1 to N = 3+2=5
Your Task: 
You don't need to read input or print anything. Your task is to complete the function solve() which takes the N (the number of vertices) ,M (the number of Edges) and the array Edges[] (Where Edges[i] denoting an undirected edge between Edges[i][0] and Edges[i][1] with a flow capacity of Edges[i][2]), and returns the integer denoting the maximum flow from 1 to N.
Expected Time Complexity: O(max_flow*M)
Expected Auxiliary Space: O(N+M)
Where max_flow is the maximum flow from 1 to N
Constraints:
1 <= N,M,Edges[i][2] <= 1000
1 <= Edges[i][0],Edges[i][1] <= N
0
vinaykumarjonnada1 week ago
ALERT , THERE MIGHT BE DIFFERENT WEIGHTS BETWEEN THE SAME EDGES, SO ADD ALL THE WEIGHTS
1→6 WEIGHT = 9 AND THEY ALSO GIVEN 6→1 WEIGHT = 7
6 101 6 9 3 2 7 6 1 7 5 1 2 5 3 2 5 4 5 3 2 8 2 2 8 3 5 9 2 3 3
+1
dipeshmishra6261 week ago
what is wrong with gfg? u don't know how to describe a question? how can sm1 solve a question by knowing half question? I have seen maxm hard problems in graphs on gfg are half explained . it is not necessary to give 1000s of ques on a topic but when u post a ques make sure it is posted with good description.Thank u.
 
+2
akshitasinghal44443 weeks ago
C++
int bfs(int source,int sink,vector<vector<int>> &g,int n,vector<int> &parent)
    {
        queue<pair<int,int>> q;
        vector<bool> vis(n,0);
        q.push({source, INT_MAX});
        vis[source]=1;
        
        while(!q.empty())
        {
            source=q.front().first;
            int cap=q.front().second;
            q.pop();
            
            for(int i=0;i<n;i++)
            {
                if(g[source][i] && !vis[i])
                {
                    parent[i]=source;
                    
                    if(i==sink)
                        return min(cap,g[source][i]);
                        
                    q.push({i,min(cap,g[source][i])});
                    vis[i]=1;
                }
            }
        }
        return 0;
    }
    
int ford_fulkerson(int source,int sink,vector<vector<int>> &g,int n)
    {
        int flow=0;
        vector<int> parent(n,-1);
        
        int min_cap;
        while(min_cap=bfs(source,sink,g,n,parent))
        {
            flow+=min_cap;
            
            int u,v=sink;
            while(v!=source)
            {
                u=parent[v];
                g[u][v]-=min_cap;
                g[v][u]+=min_cap;
                v=u;
            }
        }
        
        return flow;
    }
    
    int solve(int n,int m,vector<vector<int>> e)
    {
        vector<vector<int>> g(n+1,vector<int>(n+1,0));
        int i;
        
        for(i=0;i<m;i++)
        {
            g[e[i][0]][e[i][1]]+=e[i][2];
            g[e[i][1]][e[i][0]]+=e[i][2];
        }
        
        return ford_fulkerson(1,n,g,n+1);
    }
+2
pyatasandeep3 weeks ago
Worst ever question explanation I've ever seen :/
0
wjyjobs3 weeks ago
class Solution:
    def solve(self, N, M, Edges): 

        # graph is matrix: dim is the name of node and val is the capacity
        graph = [[0]*N for _ in range(N)]
        for (frm, to, flow) in Edges:
            graph[frm-1][to-1] += flow
            graph[to-1][frm-1] += flow
        
    
        def bfs(s, t, parent):
            q = [(s, float('inf'))]
            
            while q:
                cur, flow = q.pop(0)
                for nxt, capacity in enumerate(graph[cur]):
                    if parent[nxt] is None and capacity > 0: # not visited and has capactiy
                        parent[nxt] = cur
                        new_flow = min(flow, capacity)
                        if nxt == t: # find the destination
                            return new_flow 
                        q.append((nxt, new_flow))
                        
            return 0
            
        def maxflow(s, t):
            flow = 0
            while True:
                parent = [None]*N
                parent[s] = -1 # to mark the start node has been visited.
                new_flow = bfs(s, t, parent)
                if new_flow == 0:
                    break
                flow += new_flow
                # backtrack the path and update the flow graph
                
                cur = t
                while cur != s:
                    prev = parent[cur]
                    graph[prev][cur] -= new_flow
                    graph[cur][prev] += new_flow
                    cur = prev
            
            return flow
            
        return maxflow(0, N-1)
+6
srimadhan113 weeks ago
In the question, it is mentioned that the edges are undirected. But the following is one of the hidden testcase, where we can see the edges “1 → 6” (with flow capacity 9) and “6 → 1” (with flow capacity 7) are given.
6 10
1 6 9 3 2 7 6 1 7 5 1 2 5 3 2 5 4 5 3 2 8 2 2 8 3 5 9 2 3 3
Please fix the ambiguity in the question's description, or correct the testcases.
-1
ravi145773 weeks ago
the complete solution 
int BFS(vector<vector<int>> &graph,vector<int> &parent,int source,int sink,int N)   {       int min_cap=INT_MAX;       fill(parent.begin(), parent.end(), -1);       vector<bool> visited(N,false);       queue<int> q;              q.push(source);       visited[source]=true;       parent[source]=-1;              while(q.empty()==false)       {           auto u=q.front();           q.pop();                      //adjacents                      for(int v=0;v<N;v++)           {               if(visited[v]==false && graph[u][v]!=0)               {                   if(v==sink)                   {                       parent[v]=u;                       min_cap=min(min_cap,graph[u][v]);                       return min_cap;                   }                                      q.push(v);                   visited[v]=true;                   min_cap=min(min_cap,graph[u][v]);                   parent[v]=u;               }           }       }              return 0;   }      int fordFulkerson(vector<vector<int>> &graph,int source,int sink,int N)   {       vector<int> parent(N,-1);              int res=0;              while(BFS(graph,parent,source,sink,N)!=0)       {           int min_cap=BFS(graph,parent,source,sink,N);                      res+=min_cap;                      //considering all the edged in this path.                      int v=sink;           while(v!=source)           {               int u=parent[v];               graph[u][v]-=min_cap;               graph[v][u]+=min_cap;               v=parent[v];           }       }              return res;   }
+4
shivambadrigupta3 weeks ago
Post by @pritamkr212 
NOT my post but just saving for myself so it will not get deleted
 
REALLY GFG I WANT THE REASON WHY MY COMMENT GOT DELETED
IM DOING FOR COMMUNITY AND YOU ARE DOING PARTIALITY 
NO WORRIES I WILL DO IT AGAIN
 
OKAY TO SOLVED THIS QUESTION I TAKE ALMOST 3.5+HR .BECAUSE I MIGHT BE THE SLOW CODER ,SO FOR THE TIME SAVING FOR U FELLOWS JUST FOLLOW MY STEPS TO GET THIS HARD ALGO . I KNOW THIS WILL TAKE TIME  BUT ATLAST YOU GOT SOMETING TO LEARN
 
1-→ https://youtu.be/NwenwITjMys WATCH AT 1.25X SPEED
2-→ https://youtu.be/KChvn4SNE4g WATCH AT 1.25-1.5X SPEED (WATCH LAST 4 MIN CAREFULLY)
3-→ https://youtu.be/w0-c8io12yY  WATCH AT 1.25X SPEED 
4-→ https://youtu.be/_aWooet7O_4 WATCH AT 1.25-1.5X SPEED (WATCH LAST 10MIN CAREFULLY)
 
5-→ AT LAST JUST GO THROUGH THE https://cp-algorithms.com/graph/edmonds_karp.html
 
OTHER DOCUMENTATION https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ ,,,https://www.geeksforgeeks.org/max-flow-problem-introduction/
 
HOPE THIS COMMET DO NOT GET DELETED AGAIN
 
class Solution 
{ 
    int solve(int n, int m, ArrayList<ArrayList<Integer>> edges) 
    { 
        int g[][] = new int[n][n];
        for(int i=0;i<edges.size();i++){
            int u = edges.get(i).get(0)-1;
            int v = edges.get(i).get(1)-1;
            int w = edges.get(i).get(2);
            g[u][v]+=w;
            g[v][u]+=w;
        }
        return fordfulkerson(g,0,n-1,n);
    }
    static int fordfulkerson(int[][]graph,int source,int sink,int n){
        int[]parent=new int[n];
        Arrays.fill(parent,-1);
        int res=0;
        while(bfs(graph,parent,source,sink,n)!=0){
            int min=bfs(graph,parent,source,sink,n);
            res+=min;
            int v=sink;
            while(v!=source){
                int u=parent[v];
                graph[u][v]-=min;
                graph[v][u]+=min;
                v=u;
            }
        }
        return res;
    }
    static int bfs(int[][]graph,int[] parent,int source,int sink,int n){
        int min=Integer.MAX_VALUE;
        Arrays.fill(parent,-1);
        parent[source]=-2;
        boolean[]vis=new boolean[n];
        Queue<pair>q=new LinkedList<>();
        q.add(new pair(source,min));
        while(!q.isEmpty()){
            pair curr=q.poll();
            int node =curr.x;
            int flow=curr.y;
            for(int i=0;i<n;i++){
                if(graph[node][i]!=0){
                    if(parent[i]==-1){
                        parent[i]=node;
                        int new_flow=Math.min(flow,graph[node][i]);
                        if(i==sink)return new_flow;
                        q.add(new pair(i,new_flow));
                    }
                }
            }
        }
        return 0;
    }
}


class pair{
    int x,y;
    public pair(int x,int y){
        this.x=x;
        this.y=y;
    }
}
+7
pritamkr2123 weeks ago
REALLY GFG I WANT THE REASON WHY MY COMMENT GOT DELETED
IM DOING FOR COMMUNITY AND YOU ARE DOING PARTIALITY 
NO WORRIES I WILL DO IT AGAIN
 
OKAY TO SOLVED THIS QUESTION I TAKE ALMOST 3.5+HR .BECAUSE I MIGHT BE THE SLOW CODER ,SO FOR THE TIME SAVING FOR U FELLOWS JUST FOLLOW MY STEPS TO GET THIS HARD ALGO . I KNOW THIS WILL TAKE TIME  BUT ATLAST YOU GOT SOMETING TO LEARN
 
1-→ https://youtu.be/NwenwITjMys WATCH AT 1.25X SPEED
2-→ https://youtu.be/KChvn4SNE4g WATCH AT 1.25-1.5X SPEED (WATCH LAST 4 MIN CAREFULLY)
3-→ https://youtu.be/w0-c8io12yY  WATCH AT 1.25X SPEED 
4-→ https://youtu.be/_aWooet7O_4 WATCH AT 1.25-1.5X SPEED (WATCH LAST 10MIN CAREFULLY)
 
5-→ AT LAST JUST GO THROUGH THE https://cp-algorithms.com/graph/edmonds_karp.html
 
OTHER DOCUMENTATION https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ ,,,https://www.geeksforgeeks.org/max-flow-problem-introduction/
 
HOPE THIS COMMET DO NOT GET DELETED AGAIN
 
class Solution 
{ 
    int solve(int n, int m, ArrayList<ArrayList<Integer>> edges) 
    { 
        int g[][] = new int[n][n];
        for(int i=0;i<edges.size();i++){
            int u = edges.get(i).get(0)-1;
            int v = edges.get(i).get(1)-1;
            int w = edges.get(i).get(2);
            g[u][v]+=w;
            g[v][u]+=w;
        }
        return fordfulkerson(g,0,n-1,n);
    }
    static int fordfulkerson(int[][]graph,int source,int sink,int n){
        int[]parent=new int[n];
        Arrays.fill(parent,-1);
        int res=0;
        while(bfs(graph,parent,source,sink,n)!=0){
            int min=bfs(graph,parent,source,sink,n);
            res+=min;
            int v=sink;
            while(v!=source){
                int u=parent[v];
                graph[u][v]-=min;
                graph[v][u]+=min;
                v=u;
            }
        }
        return res;
    }
    static int bfs(int[][]graph,int[] parent,int source,int sink,int n){
        int min=Integer.MAX_VALUE;
        Arrays.fill(parent,-1);
        parent[source]=-2;
        boolean[]vis=new boolean[n];
        Queue<pair>q=new LinkedList<>();
        q.add(new pair(source,min));
        while(!q.isEmpty()){
            pair curr=q.poll();
            int node =curr.x;
            int flow=curr.y;
            for(int i=0;i<n;i++){
                if(graph[node][i]!=0){
                    if(parent[i]==-1){
                        parent[i]=node;
                        int new_flow=Math.min(flow,graph[node][i]);
                        if(i==sink)return new_flow;
                        q.add(new pair(i,new_flow));
                    }
                }
            }
        }
        return 0;
    }
}


class pair{
    int x,y;
    public pair(int x,int y){
        this.x=x;
        this.y=y;
    }
}

+1
pritamkr212
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.