diff --git a/matrix/binary_search_matrix.py b/matrix/binary_search_matrix.py index 6f203b7a3484..ca55400d27f3 100644 --- a/matrix/binary_search_matrix.py +++ b/matrix/binary_search_matrix.py @@ -9,6 +9,10 @@ def binary_search(array: list, lower_bound: int, upper_bound: int, value: int) - 0 >>> binary_search(matrix, 0, len(matrix) - 1, 23) -1 + >>> binary_search(matrix, 0, len(matrix) - 1, 15) + 4 + >>> binary_search(matrix, 0, len(matrix) - 1, 7) + 2 """ r = int((lower_bound + upper_bound) // 2) @@ -39,6 +43,21 @@ def mat_bin_search(value: int, matrix: list) -> list: >>> target = 34 >>> mat_bin_search(target, matrix) [-1, -1] + >>> target = 5 + >>> mat_bin_search(target, matrix) + [1, 1] + >>> target = 23 + >>> mat_bin_search(target, matrix) + [4, 2] + >>> target = 30 + >>> mat_bin_search(target, matrix) + [4, 4] + >>> target = 19 + >>> mat_bin_search(target, matrix) + [1, 4] + >>> target = 20 + >>> mat_bin_search(target, matrix) + [-1, -1] """ index = 0 if matrix[index][0] == value: diff --git a/networking_flow/ford_fulkerson.py b/networking_flow/ford_fulkerson.py index 716ed508e679..674685a14b65 100644 --- a/networking_flow/ford_fulkerson.py +++ b/networking_flow/ford_fulkerson.py @@ -6,15 +6,32 @@ """ -def bfs(graph, s, t, parent): - # Return True if there is node that has not iterated. - visited = [False] * len(graph) - queue = [] +def bfs(graph: list, s: int, t: int, parent: list) -> bool: + """ + This function returns True if there is node that has not iterated. + + Args: + graph (list): Adjacency matrix of graph + s (int): Source + t (int): Sink + parent (list): Parent list + + Returns: + bool: True if there is node that has not iterated. + """ + + visited = [False] * len(graph) # Mark all nodes as not visited + queue = [] # BFS queue + + # Source node queue.append(s) visited[s] = True while queue: + # Pop the front node u = queue.pop(0) + + # Traverse all adjacent nodes of u for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) @@ -24,12 +41,24 @@ def bfs(graph, s, t, parent): return visited[t] -def ford_fulkerson(graph, source, sink): +def ford_fulkerson(graph: list, source: int, sink: int) -> int: + """ + This function returns maximum flow from source to sink in given graph. + + Args: + graph (list): Adjacency matrix of graph + source (int): Source + sink (int): Sink + + Returns: + int: Maximum flow + """ + # This array is filled by BFS and to store path parent = [-1] * (len(graph)) max_flow = 0 - while bfs(graph, source, sink, parent): - path_flow = float("Inf") + while bfs(graph, source, sink, parent): # While there is path from source to sink + path_flow = int(1e9) # Infinite value s = sink while s != source: @@ -45,6 +74,7 @@ def ford_fulkerson(graph, source, sink): graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] + return max_flow