
function l = per(f, R, parent)
    b = zeros(size(f));
    l = zeros(size(f));
    
    for a = unique(f)'
        g = f >= a;
        c = zeros(size(f));
        
        c = c | g > [zeros(1, size(g, 2)); g(1:end-1, :)]; % n
        c = c | g > [zeros(size(g, 1), 1), g(:, 1:end-1)]; % e
        c = c | g > [g(2:end, :);   zeros(1, size(g, 2))]; % s
        c = c | g > [g(:, 2:end),   zeros(size(f, 1), 1)]; % e
        
        b = b + c;
    end
    
    [_, s] = sort(f(:), "descend");
    
    for x = s'
        y = x;
        
        while b(x) > 0
            l(y) = l(y) + 1;
            b(x) = b(x) - 1;
            y = parent(y);
        end
    end
end
