import numpy as np


#pythran export apply_gravity(int[][])

def apply_gravity(terrain):
    """Can handle 10k sand grains in 800ms."""
    while True:
        tops = terrain > 3
        if not np.any(tops):
            return
        terrain[tops] -= 4
        terrain[1:, :][tops[:-1, :]] += 1
        terrain[:-1, :][tops[1:, :]] += 1
        terrain[:, 1:][tops[:, :-1]] += 1
        terrain[:, :-1][tops[:, 1:]] += 1
