Solution based on some 2007 paper (runs in 10 mins, let's assume it's because of python).