Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by radekj
def count_neighbours(grid, row, col):
result = 0
grid_columns = len(grid[0])
grid_rows = len(grid)
#iterate through all neighbour cells
for x in range(-1, 2):
for y in range(-1, 2):
# take into account only the neighbour cells
if x or y:
cell_x, cell_y = row + x, col + y
# make sure the cell doesn't exceed the grid's dimensions
if (0 <= cell_x < grid_rows) and (0 <= cell_y < grid_columns):
# add cell value to the result
result += grid[cell_x][cell_y]
return result
March 5, 2015
Comments: