def neighbors(matrix, i, j):
    """
    neighbors returns the positions of the neighbors of cell (i,j)
    in the given matrix.

    These are always in the domain of the matrix and guaranteed
    to be valid positions.
    """
    directions = [
        # Verticals and horizontals.
        (0,  -1), (0,   1), (1,  0), (-1, 0),
        # Diagonals.
        (1,  -1), (-1, -1), (-1, 1), (1,  1)
    ]
    neighbors = []
    for direction in directions:
        # Check if horizontal directions are valid.
        if i + direction[0] >= len(matrix) or i + direction[0] < 0:
            continue
        # Check if vertical directions are valid.
        if j + direction[1] >= len(matrix) or j + direction[1] < 0:
            continue
        # If both horizontal and vertical directions are valid, add
        # this neighbor position.
        neighbors.append((i + direction[0], j + direction[1]))
    return neighbors