LeetCode之機器人大冒險

題目:

機器人初始位置在原點(0, 0)。小夥伴事先給機器人輸入一串指令command,機器人就會無限循環這條指令的步驟進行移動。指令有兩種:

U: 向y軸正方向移動一格
R: 向x軸正方向移動一格。
不幸的是,在 xy 平面上還有一些障礙物,他們的座標用obstacles表示。機器人一旦碰到障礙物就會被損毀。

給定終點座標(x, y),返回機器人能否完好地到達終點。如果能,返回true;否則返回false。

來源:力扣(LeetCode)
方法1:暴力解決,從原點開始一步一步走,每走一步判斷是否遇到障礙物及是否到達終點,但是實際在寫代碼的時候,運行提示超時,所以果斷放棄吧。

方法2:從網上看到的解決方法,因爲command是不斷重複的,所以只需要判斷到達終點前總共需要有幾輪,然後再對最後一輪單獨處理即可,處理障礙物時,將障礙物當做“目標”終點,如果能夠成功到達該“目標”終點,則整個過程失敗。

bool help(string command, int x_1, int y_1, int x, int y)
{
	int k;
	int x_0 = 0;
	int y_0 = 0;
	if (x_1 != 0 && y_1 != 0)
	{
		k = (x / x_1 < y / y_1) ? x / x_1 : y / y_1;
	}
	else if (x_1 == 0)
	{
		k = y / y_1;
	}
	else if (y_1 == 0)
	{
		k = x / x_1;
	}
	else {
		return true;
	}
	x = x - k*x_1;
	y = y - k*y_1;
	//判斷最後一次
	for (size_t i = 0; i < command.length(); i++)
	{
		if (x_0 == x && y_0 == y)
		{
			return true;
		}
		if (command.at(i) == 'R')
		{
			x_0 += 1;
		}
		else
			y_0 += 1;
	}
	return false;
}
bool robot(string command, vector<vector<int>>& obstacles, int x, int y)
{
	int x_1 = 0;
	int y_1 = 0;
	for (size_t i = 0; i < command.length(); i++)
	{
		if (command.at(i) == 'R')
		{
			x_1 += 1;
		}
		else
			y_1 += 1;
	}
	if (help(command,x_1,y_1,x,y) == false)
	{
		return false;
	}
	vector<vector<int>>::iterator iter = obstacles.begin();
	while (iter != obstacles.end())
	{
		int x_ot = (*iter).at(0);
		int y_ot = (*iter).at(1);
		if (x_ot <= x && y_ot <= y\
			&&(help(command,x_1,y_1,x_ot,y_ot) == true))
		{
			return false;
		}
		iter++;
	}
	return true;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章