Geek Logbook

Tech sea log book

Adding Numbers Around a Center Element in a 2D Grid in Python

In this post, we’ll explore how to manipulate a 2D grid in Python by adding numbers around a specific center element. This is a common problem in various applications, such as implementing a basic Minesweeper game, where you need to update the numbers around a mine.

Problem Statement

Given a 2D grid (or matrix), you want to increment the values of all elements surrounding a specific element, which we’ll denote as 9. If the element is at the edge or corner of the grid, you need to ensure that your code doesn’t attempt to access elements outside the grid boundaries.

Here’s a sample 3×3 grid:

tablero = [
    [-1, -1, -1],
    [-1,  9, -1],
    [-1, -1, -1]
]

We want to increment the values of the elements surrounding the 9 by 1. After processing, the grid should look like this:

result = [
    [ 0,  1,  0],
    [ 1,  9,  1],
    [ 0,  1,  0]
]

Initial Attempt

Let’s start with an initial approach. Here’s a function that attempts to update the grid:

def colocar_numeros(tablero):
    size = len(tablero[0])
    result_matrix = [[0] * size for i in range(size)]
    for column in range(size):
        for row in range(size):
            result_matrix[column][row] = tablero[column][row]
            if tablero[column][row] == 9:
               result_matrix[column-1][row-1] += 1  # [-1, -1]
               result_matrix[column-1][row]   += 1  # [ 0, -1]
               result_matrix[column-1][row+1] += 1  # [+1, -1]
               result_matrix[column][row-1]   += 1  # [-1,  0]
               result_matrix[column][row]     += 0  # [ 0,  0]
               result_matrix[column][row+1]   += 1  # [+1,  0]
    return result_matrix

However, you may notice that this approach has an issue: boundary conditions. The function will fail if the 9 is located at the edge or corner of the grid because it will attempt to access elements that don’t exist (e.g., column-1 or row+1 when at the edges).

The Solution: Adding Boundary Checks

To solve this, we can introduce boundary checks to ensure that we only access valid grid positions. Here’s the revised version of the function:

def colocar_numeros(tablero):
    size = len(tablero)
    result_matrix = [[0] * size for i in range(size)]
    for column in range(size):
        for row in range(size):
            result_matrix[column][row] = tablero[column][row]
            if tablero[column][row] == 9:
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        if 0 <= column + i < size and 0 <= row + j < size:
                            result_matrix[column + i][row + j] += 1
    return result_matrix

How It Works

  1. Grid Initialization: We initialize a result_matrix of the same size as the input tablero and fill it with zeros.
  2. Iterating Over the Grid: We iterate through each element in the grid using two nested loops.
  3. Boundary Checks: For each element equal to 9, we use another two nested loops to iterate over the surrounding 3×3 grid, adding 1 to each element. The boundary checks ensure that we don’t attempt to access elements outside the grid.
  4. Result: The function returns the updated grid, where the values surrounding the 9 have been incremented by 1.

Example Usage

Here’s how you can use the function:

tablero = [
    [-1, -1, -1],
    [-1,  9, -1],
    [-1, -1, -1]
]

result = colocar_numeros(tablero)
for row in result:
    print(row)

This will output:

[0, 1, 0]
[1, 9, 1]
[0, 1, 0]

Conclusion

By introducing boundary checks, we’ve successfully created a function that can increment the values around a specific element in a 2D grid without running into errors. This approach can be adapted to more complex scenarios, such as larger grids or different rules for updating surrounding elements.

This method is particularly useful in various applications, including game development, where you need to carefully manage grid boundaries to avoid runtime errors.

Tags: