Number of Bombs in Minesweeper

Given a list of location of bombsand a grid of size of r and c, return a matrix that reveals the number of bombs that surrounds a cell in the matrix. Denote bombs by -1.

For example:

input: mine_sweeping_reveal([[0,0], [0,1]], 3, 4)

output:
[[-1. -1.  1.  0.]
 [ 2.  2.  1.  0.]
 [ 0.  0.  0.  0.]]

The Idea: Initialize an empty matrix by r and c. Then places the bombs by their locations. Finally, rotate about each bomb in the matrix and add one to each cell. Overlapping bombs will accumulate upon themselves.

Complexity: O(|bombs|) time and O(1) extra space.

import numpy as np


def mine_sweeping_reveal(bombs, r, c):
    """
    :param bombs: List[List[int]] - bomb locations
    :param r: int - rows of board
    :param c: int - cols of board
    :return: List[int[int]]
    """
    # place bombs
    matrix = np.zeros((r, c))
    for b_r, b_c in bombs:
        matrix[b_r][b_c] = -1

    def is_valid(r, c, len_r, len_c):
        return 0 <= r < len_r and 0 <= c < len_c and matrix[r][c] != -1

    # rotate about bombs
    rotations = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (-1, 1), (1, -1)]
    for b_r, b_c in bombs:
        for rotation in rotations:
            n_r = b_r + rotation[0]
            n_c = b_c + rotation[1]
            if is_valid(n_r, n_c, r, c):
                matrix[n_r][n_c] += 1
    return matrix


print(mine_sweeping_reveal([[0,0], [0,1]], 3, 4))

Last updated