就一个起点,没必要回溯

    1. int movingCount(int threshold, int rows, int cols)
    2. {
    3. if(!rows || !cols)return 0;
    4. vector<vector<bool>> visited(rows, vector<bool>(cols, false));
    5. return backtrack(threshold, rows, cols, 0, 0, visited);
    6. }
    7. int backtrack(int threshold, int rows, int cols, int r, int c, vector<vector<bool>> & visited)
    8. {
    9. int count = 0;
    10. if(canEnter(threshold, r, c) && r >= 0 && r < rows && c >= 0 && c < cols && !visited[r][c]){
    11. visited[r][c] = true;
    12. count = 1 + backtrack(threshold, rows, cols, r + 1, c, visited) + backtrack(threshold, rows, cols, r, c + 1, visited) + backtrack(threshold, rows, cols, r - 1, c, visited) + backtrack(threshold, rows, cols, r, c - 1, visited);
    13. }
    14. return count;
    15. }
    16. bool canEnter(int threshold, int r, int c){
    17. int cnt = 0;
    18. while(r != 0){
    19. cnt += r % 10;
    20. r = r / 10;
    21. }
    22. while(c != 0){
    23. cnt += c % 10;
    24. c = c / 10;
    25. }
    26. if(cnt <= threshold)return true;
    27. else return false;
    28. }