题目
给你一个字符串
path
,其中
path[i]
的值可以是
'N'
、
'S'
'E'
或者
'W'
,分别表示向北、向南、向东、向西移动一个单位。
机器人从二维平面上的原点
(0, 0)
处开始出发,按
path
所指示的路径行走。
如果路径在任何位置上出现相交的情况,也就是走到之前已经走过的位置,请返回
True
;否则,返回
False
。
示例 1:
输入:path = "NES"
输出:false
解释:该路径没有在任何位置相交。
示例 2:
输入:path = "NESWW"
输出:true
解释:该路径经过原点两次。
提示:
-
1 <= path.length <= 10^4
-
仅由path
中的字符组成{'N', 'S', 'E', 'W}
解题思路
用数组记录曾经走过的路径
def isPathCrossing(self, path: str) -> bool:
pathList = list(path)
stepList = ["0 0"]
while len(pathList)>0:
# print(stepList)
step = pathList.pop(0)
lastStep = stepList[-1]
tempList = lastStep.split(" ")
x = int(tempList[0])
y = int(tempList[1])
if step == "N":
y = y +1
elif step == "S":
y = y - 1
elif step == "E":
x = x + 1
elif step == "W":
x = x - 1
newStepStr = str(x) + " " + str(y)
if newStepStr in stepList:
return True
stepList.append(newStepStr)
return False