# Leetcode 240 - Search a 2D Matrix II ### Understanding the problem

The problem statement on LeetCode reads as follows:

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

• Integers in each row are sorted in ascending from left to right.
• Integers in each column are sorted in ascending from top to bottom.

Example 1:

Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5

Output: true

Example 2:

Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20

Output: false

One way to solve this problem is to use a binary search algorithm. Since the rows and columns of the matrix are sorted in increasing order, we can use binary search to find the target value. Specifically, we can start at the top right corner of the matrix and compare the value at that position to the target value. If the value is less than the target value, we can move down one row because the values in that row will be greater than the value at the current position. If the value is greater than the target value, we can move left one column because the values in that column will be less than the value at the current position. We can repeat this process until we either find the target value or we determine that it is not in the matrix.

Now that we have a plan, let’s implement it in Python.

``````def searchMatrix(matrix, target):
# Edge case: if the matrix is empty, return False
if not matrix:
return False

# Set the initial position to the top right corner of the matrix
row = 0
col = len(matrix) - 1

# Search for the target value
while row < len(matrix) and col >= 0:
# Compare the value at the current position to the target value
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
# If the value is less than the target, move down one row
row += 1
else:
# If the value is greater than the target, move left one column
col -= 1

return False
``````