Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Two rules solution in Clear category for Minesweeper by nickie
adjacent = [(-1, -1), (-1, 0), (-1, 1),
( 0, -1), (0, 1),
( 1, -1), (1, 0), (1, 1)]
def checkio(field):
# Look for a cell that is safe to play
n, m = len(field), len(field[0])
for i in range(n):
for j in range(m):
# Consider all uncovered cells that are not mines
if 0 <= field[i][j] < 9:
# Find all surrounding cells with their values
neighbors = [(i+di, j+dj, field[i+di][j+dj])
for (di, dj) in adjacent
if 0 <= i+di < n and 0 <= j+dj < m]
# Find the unknown surrounding cells, continue if none
unknown = [t for t in neighbors if t[2] < 0]
if not unknown: continue
# Find how many surrounding cells contain mines
mines = sum(1 for t in neighbors if t[2] == 9)
# Case #1: all unknown surrounding cells are empty
if field[i][j] == mines:
return (False, unknown[0][0], unknown[0][1])
# Case #2: all unknown surrounding cells contain mines
elif field[i][j] == len(unknown) + mines:
return (True, unknown[0][0], unknown[0][1])
# If no safe cell could be found, try the upper left
if field[0][0] < 0:
return (False, 0, 0)
if __name__ == '__main__':
#These are just examples
checkio([
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
]) # [False, 0, 0]
checkio([
[0, 2, -1, -1, -1, -1, -1, -1, -1, -1],
[0, 2, -1, -1, -1, -1, -1, -1, -1, -1],
[0, 1, 1, 1, -1, -1, -1, -1, -1, -1],
[0, 0, 0, 1, -1, -1, -1, -1, -1, -1],
[0, 1, 1, 2, -1, -1, -1, -1, -1, -1],
[0, 1, -1, -1, -1, -1, -1, -1, -1, -1],
[0, 1, -1, -1, -1, -1, -1, -1, -1, -1],
[2, 1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
]) # [True, 0, 2]
Jan. 24, 2014
Comments: