Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions matrix/binary_search_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
44 changes: 37 additions & 7 deletions networking_flow/ford_fulkerson.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand All @@ -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


Expand Down