Implement backtrack algorithm