def energy_at(pixels, x, y):
    """
    Compute the energy of the image at the given (x, y) position.

    The energy of the pixel is determined by looking at the pixels surrounding
    the requested position. In the case the requested position is at the edge
    of the image, the current position is used whenever a "surrounding position"
    would go out of bounds.
    """
    
    h = len(pixels)
    w = len(pixels[0])

    #Calculate the previous and subsequent x coordinate taking care of the edges of the image
    x0 = x if x == 0 else x - 1
    x1 = x if x == w - 1 else x + 1
    #Now calculate the increments in the RGB colours
    dxr = pixels[y][x0].r - pixels[y][x1].r
    dxg = pixels[y][x0].g - pixels[y][x1].g
    dxb = pixels[y][x0].b - pixels[y][x1].b
    #This is the total increment in x
    dx = dxr * dxr + dxg * dxg + dxb * dxb

    #Ditto for y
    y0 = y if y == 0 else y - 1
    y1 = y if y == h - 1 else y + 1

    dyr = pixels[y0][x].r - pixels[y1][x].r
    dyg = pixels[y0][x].g - pixels[y1][x].g
    dyb = pixels[y0][x].b - pixels[y1][x].b
    dy = dyr * dyr + dyg * dyg + dyb * dyb

    #The energy is then the sum of the increments in both the x and y axes
    return dx + dy