面试题13:机器人的运动范围

机器人的运动范围

题目描述

m*n,机器人上下左右运行。但不能进入行+列之和大于k的格子。问机器人能到达多少个格子


int MovingCount(int threshold, int rows, int cols)
{
	if(threshold <=0 || rows<=0 || cols<=0)
		return 0;
	bool visited = new bool[rows*cols];
	for(int i=0; i<rows; i++)
	{
		for(int j=0;j<cols;j++)
		{
			visited[i][j] = 0;
		}
	}

	int count = CountCore(threshold, rows,cols,0,0,visited);
	return count;
}



int CountCore(int threshold, int rows, int cols, int row, int col, bool *visited)
{
	int count = 0;
	if(check(threshold, rows, cols, row, col, visited))
	{
		visited[row*cols + col] = true;
		count = 1+ CountCore(threshold, rows,cols,row+1,col,visited) \
		+CountCore(threshold, rows,cols,row-1,col,visited) \
		+CountCore(threshold, rows,cols,row,col+1,visited) \
		+CountCore(threshold, rows,cols,row,col-1,visited);
	}
	return count;
}

int getSum(int a, int b)
{
	int sum=0;
	int number[2] = {a, b};
	for(int i=0; i<2; i++)
	{
		int n = number[i];
		while(n!=0)
		{
			sum += n%10;
			n = n/10;
		}
	}
	return sum;
}

bool check(int threshold, int rows, int cols, int row, int col, bool *visited)
{
	if(row >=0 && row<rows && col>=0 && col<cols &&!visited[row*cols + col] 
	&& getSum(row, col)<=threshold)
	{
		return true;
	}
	return false;
}
发布了68 篇原创文章 · 获赞 2 · 访问量 6208

猜你喜欢

转载自blog.csdn.net/qq_30050175/article/details/90235118