Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by keromage
def count_neighbours(grid, row, col):
def limitation(num, u_limit):
if num < 0:
num = 0
if num > u_limit:
num = u_limit
return num
# creating a matrix 'adjacent'
n = len(grid)
adjacent = []
for i in range(n):
adjacent.append([limitation(i - 1, n - 1), limitation(i + 1, n - 1)])
# adjacent = ((0, 1), (0, 2), (1, 3), (2, 4), (3, 4)) ... ex. n = 5
# adjacent [2] = (1,3) means that row2 is adjacent to row1-3.
# Count bit around the grid using matrix
sum_of_around = 0
for i in range(adjacent[row][0], adjacent[row][1] + 1):
sum_of_around += sum(grid[i][adjacent[col][0] : adjacent[col][1] + 1])
sum_of_around -= grid[row][col]
return sum_of_around
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 1, 2) == 3, "1st example"
assert count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example"
assert count_neighbours(((1, 1, 1),
(1, 1, 1),
(1, 1, 1),), 0, 2) == 3, "Dense corner"
assert count_neighbours(((0, 0, 0),
(0, 1, 0),
(0, 0, 0),), 1, 1) == 0, "Single"
Jan. 3, 2021