面试题13:机器人的运动范围(回溯、C++)

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值