Rules are super simple: We take as input a grid of where the mines are, and we output a grid where each cell represents the number of mines explicitly around it.
This means we need to check at 8 spots for each cell: Top left, Top Middle, Top Right, Middle Right, Middle Left, Bottom Left, Bottom Middle, and Bottom Right. If any of these cells contain a mine, the cell we are checking it for becomes the NUMBER of mines we have just counted.
Example Input:
input = ["OOOXXXOXX", "XXXXXXOXX", "XOOXXXXXX", "OOXXOXOXX", "XXXXXXXXX"]
For which we output:
2 3 4 X X X 4 X X
X X X X X X 7 X X
X 5 6 X X X X X X
3 5 X X 8 X 8 X X
X X X X X X X X X
Now here is my working solution:
def minesweeper(array):
# Vertical iterations
for lineIndex in range(len(array)):
line = array[lineIndex]
outputLine = []
# Horizontal iterations
for cellIndex in range(len(line)):
# Check cell content
if (line[cellIndex] == "O"):
northIndex = lineIndex - 1
eastIndex = cellIndex - 1
southIndex = lineIndex + 1
westIndex = cellIndex + 1
verticals = [northIndex, lineIndex, southIndex]
horizontals = [eastIndex, cellIndex, westIndex]
counter = 0
for v in verticals:
for h in horizontals:
if v >= 0 and h >= 0:
if array[v][h] == 'X':
counter += 1
outputLine.append(str(counter))
else:
outputLine.append("X")
print(' '.join(outputLine))
I believe there must be a better solution in terms of space-time complexity and just in general. I was given 15 minutes to solve this in a coding challenge, and still can't figure out for the life of me how someone would have approached this.