Given a weighted graph of N vertices numbered from 0 to N-1 in the form of adjacency matrix A[ ][ ] and two integers S denoting the number of source vertex and T denoting the number of sink vertex. The task is to find minimum capacity s-t cut of the given network. An s-t cut is a cut that requires the source node ‘S’ and the sink node ‘T’ to be in different subsets, and it consists of edges going from the source’s side to the sink’s side. The capacity of an s-t cut is defined by the sum of the capacity of each edge in the cut-set. In other words, you have to find out all the edges which has to be removed to make it impossible to reach the sink node from source node, and the edges you select should have a minimum sum of weights. You have to return all the edges included in the minimum capacity s-t cut and if there are no edges in minimum capacity s-t cut, return "-1".
Example 1:
Input:
N = 2
A[][] = [[0, 3],
         [0, 0]]
S = 0
T = 1
Output:
0 1
Explanation: We have to remove the edge going
from 0^{th} vertex to 1^{st} vertex.
 
Example 2:
Input:
N = 5
A[][] = [[0, 0, 0, 0, 0],
         [0, 0, 2, 3, 0],
         [0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0]]
S = 0
T = 4
Output:
-1
Explanation: There are no edges in 
minimum capacity s-t cut.
Your Task: 
You don't need to read input or print anything. Your task is to complete the function minimumCut() which takes the adjacency matrix A[ ][ ], source node number S, sink node number T and number of vertices N and returns a list of integers res[ ] where res[2*i-1] and res[2*i] denotes an edge in minimum capacity s-t cut where 1 ≤ i ≤ length(res)/2, if there are no edges in minimum capacity s-t cut, return only one integer "-1" in res[ ].
Expected Time Complexity: O(max_flow * N^{2})
Expected Auxiliary Space: O(N^{2})
Constraints:
1 ≤ N ≤ 50
0 ≤ S, T < N

Source: geeksforgeeks | Difficulty: MEDIUM_HARD
Tags: Graph algorithms

Data structures

Starter code: #User function Template for python3
    
class Solution:
    def minimumCut(self, A, S, T, N):
        #code here

Solutions:
from collections import defaultdict, deque
import copy

class Graph:

	def __init__(self, graph):
		self.graph = graph
		self.org_graph = [i[:] for i in graph]
		self.ROW = len(graph)
		self.COL = len(graph[0])

	def BFS(self, s, t, parent):
		visited = [False] * self.ROW
		queue = []
		queue.append(s)
		visited[s] = True
		while queue:
			u = queue.pop(0)
			for (ind, val) in enumerate(self.graph[u]):
				if visited[ind] == False and val > 0:
					queue.append(ind)
					visited[ind] = True
					parent[ind] = u
		return True if visited[t] else False

	def dfs(self, graph, s, visited):
		visited[s] = True
		for i in range(len(graph)):
			if graph[s][i] > 0 and (not visited[i]):
				self.dfs(graph, i, visited)

	def minCut(self, source, sink):
		parent = [-1] * self.ROW
		max_flow = 0
		s = -1
		while self.BFS(source, sink, parent):
			path_flow = float('Inf')
			s = sink
			while s != source:
				path_flow = min(path_flow, self.graph[parent[s]][s])
				s = parent[s]
			max_flow += path_flow
			v = sink
			while v != source:
				u = parent[v]
				self.graph[u][v] -= path_flow
				self.graph[v][u] += path_flow
				v = parent[v]
		if s != -1:
			visited = len(self.graph) * [False]
			self.dfs(self.graph, s, visited)
			cut_list = []
			for i in range(self.ROW):
				for j in range(self.COL):
					if self.graph[i][j] == 0 and self.org_graph[i][j] > 0 and visited[i]:
						cut_list.append(str(i) + ' ' + str(j))
			return cut_list
		return []

class Solution:

	def build_directed_graph(self, Graph):
		Directed_Graph = {}
		mapping_data = {}
		for node in Graph.keys():
			mapping_data[str(node)] = node
			if 'forward' + str(node) not in Directed_Graph.keys():
				Directed_Graph['forward' + str(node)] = defaultdict(int)
			Directed_Graph['forward' + str(node)]['backwar' + str(node)] += 1
		for source in Graph.keys():
			for target in Graph[source]:
				mapping_data[str(source)] = source
				mapping_data[str(target)] = target
				if 'backwar' + str(source) not in Directed_Graph.keys():
					Directed_Graph['backwar' + str(source)] = defaultdict(int)
				Directed_Graph['backwar' + str(source)]['forward' + str(target)] += 1
		return (Directed_Graph, mapping_data)

	def BFS(self, graph, s, t, parent):
		visited = defaultdict(int)
		queue = deque()
		queue.append(s)
		visited[s] = True
		while bool(queue):
			popped_vertex = queue.popleft()
			if graph.get(popped_vertex, 0):
				for vertex in graph[popped_vertex].keys():
					val = graph[popped_vertex][vertex]
					if visited[vertex] == False and val > 0:
						queue.append(vertex)
						visited[vertex] = True
						parent[vertex] = popped_vertex
		return True if visited[t] else False

	def dfs(self, graph, s, visited):
		visited[s] = True
		for i in range(len(graph)):
			if graph[s][i] > 0 and (not visited[i]):
				self.dfs(graph, i, visited)

	def minCut(self, graph, source, sink):
		parent = defaultdict(int)
		s = -1
		max_flow = 0
		edge_cut = []
		new_graph = {}
		for i in graph.keys():
			new_graph[i] = defaultdict(int)
			for j in graph[i].keys():
				new_graph[i][j] = graph[i][j]
		while self.BFS(new_graph, source, sink, parent):
			path_flow = float('Inf')
			s = sink
			while s != source:
				path_flow = min(path_flow, new_graph[parent[s]][s])
				s = parent[s]
			max_flow += path_flow
			v = sink
			while v != source:
				u = parent[v]
				new_graph[u][v] -= path_flow
				new_graph[v][u] += path_flow
				v = parent[v]
		if s != -1:
			visited = defaultdict(int)
			self.dfs(new_graph, s, visited)
			for i in sorted(graph.keys()):
				for j in sorted(graph[i].keys()):
					if visited[i] and (not visited[j]) and graph[i][j]:
						edge_cut.append(str(i) + ' ' + str(j))
		return edge_cut

	def minimumCut(self, graph, S, T, N):
		Graph = {}
		for i in range(len(graph)):
			for j in range(len(graph[i])):
				graph[i][j] = int(graph[i][j])
		vertices = [0, 1, 2, 3, 4]
		for vertex in range(len(graph)):
			Graph[vertex] = defaultdict(int)
		for i in range(len(graph)):
			for j in range(len(graph[i])):
				Graph[i][j] = graph[i][j]
		val = self.minCut(Graph, S, T)
		if val == []:
			return [-1]
		return val


class Solution:

	def minimumCut(self, A, S, T, N):
		ans = []
		breaker = 0
		start = S
		end = T
		adj = [[] for i in range(N)]
		scores = {}
		for u in range(N):
			for v in range(N):
				adj[u].append(v)
				scores[u, v] = A[u][v]
		while breaker == 0:
			visited = [False for x in range(N)]
			(tflow, tnodes) = self.BFS(start, end, adj, visited, scores)
			if tflow > 0:
				for i in range(len(tnodes) - 1):
					u = tnodes[i]
					v = tnodes[i + 1]
					scores[u, v] -= tflow
					scores[v, u] += tflow
			else:
				breaker = 1
		visited = [False for x in range(N)]
		visited = self.findReachable(start, scores, adj, visited)
		for i in range(N):
			for j in range(N):
				if A[i][j] > 0:
					if visited[i] and (not visited[j]):
						ans.append(i)
						ans.append(j)
		if len(ans) == 0:
			return [-1]
		return ans

	def findReachable(self, start, scores, adj, visited):
		visited[start] = True
		for nei in adj[start]:
			weight = scores[start, nei]
			if visited[nei] or weight == 0:
				continue
			visited = self.findReachable(nei, scores, adj, visited)
		return visited

	def BFS(self, start, end, adj, visited, scores):
		tnodes = [start]
		tflow = 0
		visited[start] = True
		for nei in adj[start]:
			weight = scores[start, nei]
			if visited[nei] or weight == 0:
				continue
			if nei == end:
				tnodes.append(end)
				tflow = weight
				return (tflow, tnodes)
			(tflow2, tnodes2) = self.BFS(nei, end, adj, visited, scores)
			if tflow2 > 0:
				tflow = min(weight, tflow2)
				tnodes = tnodes + tnodes2
				return (tflow, tnodes)
		return (tflow, tnodes)