def neighbors(mat, i, j):
    """
    given a matrix mat and indexes i, j return the indexes of all mat[i, j] neighbors
    thus excluding negative and out of range indexes
    """
    imax, jmax = mat.shape
    valid_neighbors = []
    possible_neighbors = [(i-1, j), (i+1, j), (i, j-1), (i, j+1),
                          (i-1, j-1), (i-1, j+1), (i+1, j-1), (i+1, j+1)]
    for neighbor in possible_neighbors:
        if neighbor[0] >= 0 and neighbor[1] >= 0 and neighbor[0] < imax and neighbor[1] < jmax:
            valid_neighbors.append(neighbor)
    return valid_neighbors