finished backtrack algorithm with bugs