สมมติว่าหุ่นยนต์อยู่ที่ (0,0) มีรายการการเคลื่อนที่ N, S, W, E ต้องตรวจสอบว่าสามารถไปถึงพิกัด (x,y) ได้หรือไม่
ตัวอย่าง: moves = ['N','N','E','E','S'], coord = [2,1] ผลลัพธ์ True
ขั้นตอนการแก้ปัญหา (Simulation)
temp_coord = [0, 0]- สำหรับแต่ละ
move:- N:
temp_coord[1] += 1 - S:
temp_coord[1] -= 1 - E:
temp_coord[0] += 1 - W:
temp_coord[0] -= 1
- N:
- คืนค่า
temp_coord == coord
ตัวอย่างโค้ด Python
class Solution:
def solve(self, moves, coord):
temp_coord = [0, 0]
for move in moves:
if move == "N":
temp_coord[1] += 1
elif move == "S":
temp_coord[1] -= 1
elif move == "E":
temp_coord[0] += 1
elif move == "W":
temp_coord[0] -= 1
return temp_coord[0] == coord[0] and temp_coord[1] == coord[1]
ob = Solution()
moves = ['N', 'N', 'E', 'E', 'S']
coord = [2, 1]
print(ob.solve(moves, coord)) # Output: True
อินพุต
['N', 'N', 'E', 'E', 'S'], [2, 1]
เอาต์พุต
True