I am stuck on a problem on Codefights. Here is the description:
In the popular Minesweeper game you have a board with some mines and those cells that don't contain a mine have a number in it that indicates the total number of mines in the neighboring cells. Starting off with some arrangement of mines we want to create a Minesweeper game setup.
Example
For
matrix = [[True, False, False],
[False, True, False],
[False, False, False]]
The output should be:
minesweeper(matrix) = [[1, 2, 1],
[2, 1, 1],
[1, 1, 1]]
So from what I understand, we have to look trough the whole matrix because we need to know which cells are True, i.e contains a bomb, then when we find one, all neighbouring cells' value should be incremented by 1. I first tried to write the code using if/elif statements for the border cells (to not throw an error) but the code became really ugly and long. So the only thing I could come up with was this:
def minesweeper(matrix):
# First creating the same matrix but instead full of zeros.
result = [[0]* len(matrix[0]) for row in matrix]
# Start iterating through the original matrix to find True elements
for y in range(len(matrix)):
for x in range(len(matrix[0])):
if matrix[y][x] == True:
# The remaining code tries to increment all possible neighbours by 1.
for j in range(-1,2):
for i in range(-1,2):
# If statement so that we do not increment the bomb cell itself.
if not (j == 0 and i == 0):
try:
result[y+j][x+i] += 1
except:
continue
return result
The output of my function for
input = [[True, False, False],
[False, True, False],
[False, False, False]]
is
[[1, 2, 2], [2, 1, 2], [2, 2, 2]]
Anyone has an idea why it doesnt work? And I also know that you should try to catch error with try/except statements and that this probably is bad practice, I just couldnt figure out another way without the super long if/elif statements.