function mask = trace( M, costs, randomness )
[m, n] = size(costs);
mask = zeros(m, n);
starts = randperm(n);
iteration = 0;
f = 1;
for k=1:n
    j = starts(k);
    mask(m, j) = 1;
    for i=m-1:-1:1
        r = rand();
        if r < randomness
            choice = randi(3);
        else
            [~, choice] = min(costs(i, max(1, j-1):min(n, j+1)));
        end
        if j == 1
            j = j + choice - 1;
        else
            j = j + choice - 2;
        end
        mask(i, j) = 1;
        imagesc(mask);
        pause(0.01);
        if mod(iteration, 50) == 0 && k < 50
            saveas(gcf, ['river1/', sprintf('%03d', f), '.png']);
            f = f + 1;
        end
        iteration = iteration + 1;

    end
end

end

