Python Program to find the Next Nearest element in a Matrix

Finding the next nearest element in a matrix involves searching for a specific value that appears after a given position. This is useful in applications like pathfinding, data analysis, and grid-based algorithms where you need to locate the next occurrence of a value.

Algorithm

The approach starts from a given position (x, y) and searches row by row for the target element. It first checks the remaining elements in the current row, then moves to subsequent rows.

Example

Below is a demonstration of finding the next nearest element ?

def get_nearest_elem(matrix, x, y, target):
    # Search in current row from position y+1 onwards
    for j in range(y + 1, len(matrix[x])):
        if matrix[x][j] == target:
            return x, j
    
    # Search in subsequent rows
    for i in range(x + 1, len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == target:
                return i, j
    
    return -1, -1

# Define the matrix
matrix = [[21, 32, 11, 22, 13], 
          [91, 52, 31, 26, 33], 
          [81, 52, 3, 22, 3], 
          [11, 92, 83, 4, 9]]

print("The matrix is:")
for row in matrix:
    print(row)

# Starting position and target value
start_x, start_y = 1, 3
target = 3

print(f"\nSearching for '{target}' after position ({start_x}, {start_y})")

result_x, result_y = get_nearest_elem(matrix, start_x, start_y, target)

if result_x != -1:
    print(f"Found '{target}' at position: ({result_x}, {result_y})")
else:
    print(f"Element '{target}' not found after the given position")

The output of the above code is ?

The matrix is:
[21, 32, 11, 22, 13]
[91, 52, 31, 26, 33]
[81, 52, 3, 22, 3]
[11, 92, 83, 4, 9]

Searching for '3' after position (1, 3)
Found '3' at position: (2, 2)

How It Works

The function follows these steps:

  • Current Row Search: First checks remaining elements in the current row from position y+1 onwards
  • Subsequent Rows: If not found in current row, searches all elements in subsequent rows
  • Return Position: Returns the coordinates (row, column) of the first occurrence, or (-1, -1) if not found

Alternative Implementation

Here's a more comprehensive version that finds all occurrences ?

def find_all_nearest_elements(matrix, x, y, target):
    positions = []
    
    # Search in current row
    for j in range(y + 1, len(matrix[x])):
        if matrix[x][j] == target:
            positions.append((x, j))
    
    # Search in subsequent rows
    for i in range(x + 1, len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == target:
                positions.append((i, j))
    
    return positions

matrix = [[1, 2, 3, 4], 
          [5, 6, 3, 8], 
          [9, 3, 11, 3]]

start_x, start_y = 0, 1
target = 3

all_positions = find_all_nearest_elements(matrix, start_x, start_y, target)
print(f"All positions of '{target}' after ({start_x}, {start_y}): {all_positions}")
All positions of '3' after (0, 1): [(0, 2), (1, 2), (2, 1), (2, 3)]

Conclusion

This algorithm efficiently finds the next nearest element in a matrix by searching row-wise from a given starting position. It's particularly useful for grid-based search operations and can be extended to find all occurrences or implement distance-based nearest neighbor searches.

Updated on: 2026-03-26T02:06:19+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements