题目链接:
思路:
参考https://leetcode-cn.com/problems/programmable-robot/solution/jian-dan-fang-fa-wu-hash-by-asver0521/
题目要求返回是否完好到达终点,而终点(x,y)0 <= x <= 1e9, 0 <= y <= 1e9,所以暴力算路径会超时。
所幸在于指令command是一种循环,实际上每一层循环的坐标都是第一次循环UR数量的倍数加上基础坐标。
这样就可以求得,只要任何一个obstacle在路径上,就可以输出false。
所以只用匹配每个obstacle是否在循环路径中。
变成了一道初中数学问题。
xn = nx + x1
yn = ny + y1
反向求解即可
def robot(self, command: str, obstacles: List[List[int]], x: int, y: int) -> bool:
a, b = 0, 0
path = [[0,0]]
#第一次循环的路径,作为基础坐标(x1, y1)
for v in command:
if v == "U":
b += 1
else:
a += 1
path.append([a, b])
#判断终点是否能到达
if [x % path[-1][0] , y - ((x // path[-1][0]) * path[-1][1])] not in path:
return False
#判断ob在终点范围以内,再判断是否在循环路径中
for ob in obstacles:
if ob[0] <= x and ob[1] <= y:
if [ob[0] % path[-1][0] , ob[1] - ((ob[0] // path[-1][0]) * path[-1][1])] in path:
return False
return True
**************************************************************************************************************************************
按照我一开始的思路用回溯法去做会超时。
回溯:
class Solution(object):
def robot(self, command, obstacles, x, y):
"""
:type command: str
:type obstacles: List[List[int]]
:type x: int
:type y: int
:rtype: bool
"""
return self.FindPath(command, obstacles, x, y, 0, 0, 0)
def FindPath(self,command, obstacles, x, y, i, j, k):
if i == x and j == y:
return True
if obstacles and [i,j] in obstacles:
return False
if k >= len(command):
k = 0
if command[k] == 'U':
nxt = self.FindPath(command, obstacles, x, y, i, j+1, k+1)
elif command[k] == 'R':
nxt = self.FindPath(command, obstacles, x, y, i+1, j, k+1)
return nxt