1

I want to make something similiar to minesweeper

input matrix:

matrix = [[true, false, false],
          [false, true, false],
          [false, false, false]]

if a bomb is on the field I do not count it as bomb is surrounding.

I thought about doing it with numpy convolve somehow but I am struggling with how to go through the matrix and always check the left, top, right and bottom fields of the actual field (in the case of a border I check "empty" fields which is 0 for sure)

enter image description here

Dominik Lemberger
  • 2,287
  • 2
  • 21
  • 33

3 Answers3

5

Here is a solution using scipy.signal.convolve2d :

import scipy
import numpy as np

# Input matrix, can be left as boolean
matrix = np.array([[True, False, False],
                   [False, True, False],
                   [False, False, False]])

# Our dougnut filter
W = np.array([[1, 1, 1],
              [1, 0, 1],
              [1, 1, 1]])

# Single convolve
res = convolve2d(matrix, W, 'same')

We get the exact result:

res
array([[1, 2, 1],
       [2, 1, 1],
       [1, 1, 1]])
ibarrond
  • 6,617
  • 4
  • 26
  • 45
1

using only numpy, including nd_window from here

m_pad = np.pad(matrix, ((1,1),(1,1)), 'constant', constant_values=(False, False))
filter = np.array([[1,1,1],[1,0,1],[1,1,1]], dtype = bool)
adj_matrix = np.einsum('ijkl,kl->ij', nd_window(m_pad, 3), filter)

Also, you can use scipy.signal.convolve2d

adj_matrix = convolve2d(matrix, filter, 'same', fillvalue = False)
Daniel F
  • 13,620
  • 2
  • 29
  • 55
0

To keep it simple : using numpy you can simply use the sum() method (https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matrix.sum.html).

np.matrix(matrix).sum() will count all the True in your matrix.

So np.matrix(matrix).sum() - matrix[1][1] should return the number of mine around a cell.

And for me the easiest way to remove the border problem is to complete your matrix with False cells all around it.

Louis
  • 87
  • 8