Refactor and improve solving speed