finished backtrackting algorithm with minor bugs