题解 | #机器人的运动范围#

机器人的运动范围

http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8





int8_t Check_k(int k, int row, int col)
{
	int tmp_r = 0;
	int tmp_c = 0;
	while (row )
	{
		tmp_r += row % 10;
		row /= 10;
	}
	while (col)
	{
		tmp_c += col % 10;
		col /= 10;
	}
	if(tmp_r + tmp_c <= k)
        return 1;
    else
        return 0;
}

int8_t Check_Path(int k, int m, int n, int row, int col, int8_t* visited)
{
	if (row >= 0 && row < m && col >= 0 && col < n
		&& Check_k(k, row, col) && (!visited[row * n + col]))
		return 1;
	else
		return 0;
}

void Path_Core(int k,int m,int n,int  row,int  col, int8_t* visited)
{
	if (row < 0 || row >= m || col < 0 || col >= n )
		return;

	if (Check_Path(k, m, n, row, col, visited))
	{
		visited[row * n + col] = 1;
		Path_Core(k, m, n, row - 1, col, visited);
		Path_Core(k, m, n, row + 1, col, visited);
		Path_Core(k, m, n, row, col + 1, visited);
		Path_Core(k, m, n, row, col - 1, visited);
	}

}

int Num_reachable(int k, int m, int n)
{
	int i;
	int Len = 0;
	int count = 0;
	int8_t* visited = (int8_t*)malloc(sizeof(int8_t) * m * n );

	if (k < 0 || m < 0 || n < 0)
		return 0;
	for (i = 0; i < m * n; i++)
		visited[i] = 0;

	Path_Core(k,m, n, 0, 0, visited);
    
    for (i = 0; i < m * n; i++)
		count+=visited[i];
    
	free(visited);
	return count;

}




int movingCount(int threshold, int rows, int cols ) {
    return Num_reachable(threshold,rows,cols);
}
全部评论

相关推荐

尊嘟假嘟点击就送:加v细说,问题很大
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务