test = [[0, 19, 5, 11], [4, 0, 18, 0], [13, 9, 0, 1], [3, 13, 14, 0]] from collections import deque def bfs(matrix): q = deque() used = [-1] * (len(matrix)) used[0] = True q.append(0) while q: now = q[0] q.popleft() for i in range(0, (len(matrix[now]))): if (matrix[now][i] != 0 and used[i] == -1): q.append(i) used[i] = now return used def pathGet(Story): result = deque() used = [False] * (len(Story) + 1) i = 1 while ((i != 0)): if used[i] == False: result.appendleft(i) i = Story[i] used[i] = True result.appendleft(0) return result def FordFukerson(matrix): c = matrix path_matrix = bfs(c) while path_matrix[1] != -1: i = 1 path = pathGet(path_matrix) m = c[path[0]][path[1]] for i in range(0, len(path) - 1): a = path[i] b = path[i + 1] if c[a][b] < m: m = c[a][b] for i in range(0, len(path) - 1): a = path[i] b = path[i + 1] matrix[a][b] -= m matrix[b][a] += m c[a][b] += m c[b][a] -= m path_matrix = bfs(c) result = 0 for i in matrix[0]: result += i return result print(FordFukerson(test))