You are given ‘N’ = 4, ‘M’ = 3 and ‘PIPES’ = [[1, 2, 2], [1, 3, 4], [3, 4, 3]]. The maximum flow will be 3. The graph will look like this:
The maximum flow will be 3 because 4 units of water can flow from 1 -> 3, and 3 units of water can flow from 3 -> 4.
The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, representing the numbers of houses and pipes, respectively.
The next line ‘M’ lines contain three space-separated integers representing a pipe.
For each test case, print the maximum flow of water from house 1 to house N.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 500
1 <= M <= (N*(N-1))/2
1 <= PIPES[i][0] <= N
1 <= PIPES[i][1] <= N
1 <= PIPES[i][2] <= 500
Time Limit: 1 sec
Prerequisite: Ford-Fulkerson algorithm.
We will use the Ford-Fulkerson algorithm to find the maximum flow. It is a greedy algorithm that computes the maximum flow in a flow network.
The basic idea behind the Ford-Fulkerson algorithm is that as long as there is a path from the source (start node) to the sink (end node), with available capacity on all edges in the path, we send flow along with one of the paths. Then we find another path, and so on.
Terminologies:
To check whether a path exists from the source to the sink, we will use BFS. BFS is a traversing algorithm where you should start traversing from a start node and traverse the graphs layer-wise. We will use the ‘VISITED’ array to keep track of all the visited nodes, and if VISITED[SINK] is true, there is a path from the source to the sink.
Algorithm :
Maintain a function ‘FORDFULKERSON(INT SOURCE, INT SINK, INT[][] GRAPH)’:
Maintain a function ‘BFS(INT[][] RESIDUALGRAPH, INT SRC, INT DEST, INT[] PARENT)’: