From 85f6642f6eca968249d84bbeeae1d78c3a8934b8 Mon Sep 17 00:00:00 2001 From: Payal Padmalaya Prusty <98264541+PayalPadmalyaPrusty@users.noreply.github.com> Date: Sat, 20 May 2023 16:48:44 +0530 Subject: [PATCH] #157 solved --- matrix.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 matrix.py diff --git a/matrix.py b/matrix.py new file mode 100644 index 0000000..857b4f4 --- /dev/null +++ b/matrix.py @@ -0,0 +1,33 @@ +def search_matrix(matrix, target): + if not matrix or not matrix[0]: + return False + + rows = len(matrix) + cols = len(matrix[0]) + + # Start at the top-right corner + row = 0 + col = cols - 1 + + while row < rows and col >= 0: + if matrix[row][col] == target: + return True + elif matrix[row][col] < target: + row += 1 + else: + col -= 1 + + return False + + +matrix = [ + [1, 2, 3, 4, 5], + [2, 6, 7, 8, 9], + [3, 10, 19, 16, 22], + [4, 13, 14, 17, 24], + [5, 21, 23, 26, 30] +] + +target = 21 +result = search_matrix(matrix, target) +print(f"Element {target} found in the matrix: {result}")