1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution { public: int movingCount (int threshold, int rows, int cols) { if (threshold < 1 || rows < 1 || cols < 1) return 0; bool* visit = new bool[rows * cols]; memset(visit, 0, rows * cols); int result = movingCountCore (threshold, rows, cols, 0, 0, visit); delete[] visit; return result; } private: int movingCountCore (int threshold, int rows, int cols, int row, int col, bool* visit) { int count = 0; if (row >= 0 && row < rows && col >= 0 && col < cols && getSum(row) + getSum(col) <= threshold && !visit[row * cols + col]) { visit[row * cols + col] = true; count = 1 + movingCountCore (threshold, rows, cols, row - 1, col, visit) + movingCountCore (threshold, rows, cols, row + 1, col, visit) + movingCountCore (threshold, rows, cols, row, col - 1, visit) + movingCountCore (threshold, rows, cols, row, col + 1, visit); } return count; } int getSum (int num) { int sum = 0; while (num) { sum += num%10; num /= 10; } return sum; } };
|