#include<iostream>
using std::endl;
using std::cout;
using std::cin;
class moveCount
{
bool* visited;
int _rows, _cols, _target;
public:
moveCount(int target, int rows, int cols);
~moveCount() { delete[] visited; }
private:
int moveCountCore(int row, int col);
int getSum(int num);
bool check(int row, int col);
};
bool moveCount::check( int row, int col)
{
if (row >= 0 && row < _rows && col >= 0 && col < _cols
&& !visited[row * _cols + col] && getSum(row) + getSum(col) <= _target)
return true;
return false;
}
int moveCount::moveCountCore(int row, int col)
{
int countN = 0;
if (check(row, col))
{
visited[row * _cols + col] = true;
countN = 1
+ moveCountCore(row - 1, col)
+ moveCountCore(row + 1, col)
+ moveCountCore(row, col - 1)
+ moveCountCore(row, col + 1);
}
return countN;
}
int moveCount::getSum(int num)
{
int sum = 0;
while (num)
{
sum += num % 10;
num /= 10;
}
return sum;
}
moveCount::moveCount(int target, int rows, int cols):visited(nullptr),_rows(rows),_cols(cols),_target(target)
{
int count;
if (target < 0 || rows <= 0 || cols <= 0)
{
cout << "无法统计!" << endl;
return;
}
visited = new bool[_rows * _cols];
memset(visited, 0, _rows * _cols);
count = moveCountCore(0, 0);
cout << "总计:" << count << endl;
}
int main(int argc, char* argv[])
{
moveCount A(18, -50, -50);
moveCount B(18, 50, 50);
moveCount C(18, 1, 50);
cin.get();
return 0;
}
面试题13:机器人的运动范围(回溯、C++)
最新推荐文章于 2021-10-17 00:06:10 发布