1
+ dy = [0 ,1 ,0 ,- 1 ]
2
+ dx = [1 ,0 ,- 1 ,0 ]
3
+
4
+ def solution (dirs ):
5
+ global dy
6
+ global dx
7
+ answer = 0
8
+ visited = []
9
+
10
+ start = [0 ,0 ]
11
+ for i in dirs :
12
+ if i == 'U' :
13
+ if [start ,3 ] not in visited :
14
+ visited .append ([start ,3 ])
15
+ start = [start [0 ]+ dy [1 ], start [1 ]+ dx [1 ]]
16
+ if - 5 > start [0 ] or start [0 ] > 5 or start [1 ] > 5 or start [1 ] < - 5 :
17
+ start = [start [0 ] - dy [1 ], start [1 ] - dx [1 ]]
18
+ continue
19
+ if [start ,1 ] not in visited :
20
+ visited .append ([start ,1 ])
21
+ answer += 1
22
+ elif i == 'R' :
23
+ if [start ,2 ] not in visited :
24
+ visited .append ([start ,2 ])
25
+ start = [start [0 ] + dy [0 ], start [1 ] + dx [0 ]]
26
+ if - 5 > start [0 ] or start [0 ] > 5 or start [1 ] > 5 or start [1 ] < - 5 :
27
+ start = [start [0 ] - dy [0 ], start [1 ] - dx [0 ]]
28
+ continue
29
+ if [start , 0 ] not in visited :
30
+ visited .append ([start , 0 ])
31
+ answer += 1
32
+ elif i == 'D' :
33
+ if [start ,1 ] not in visited :
34
+ visited .append ([start ,1 ])
35
+ start = [start [0 ] + dy [3 ], start [1 ] + dx [3 ]]
36
+ if - 5 > start [0 ] or start [0 ] > 5 or start [1 ] > 5 or start [1 ] < - 5 :
37
+ start = [start [0 ] - dy [3 ], start [1 ] - dx [3 ]]
38
+ continue
39
+ if [start , 3 ] not in visited :
40
+ visited .append ([start , 3 ])
41
+ answer += 1
42
+ elif i == 'L' :
43
+ if [start ,0 ] not in visited :
44
+ visited .append ([start ,0 ])
45
+ start = [start [0 ] + dy [2 ], start [1 ] + dx [2 ]]
46
+ if - 5 > start [0 ] or start [0 ] > 5 or start [1 ] > 5 or start [1 ] < - 5 :
47
+ start = [start [0 ] - dy [2 ], start [1 ] - dx [2 ]]
48
+ continue
49
+ if [start , 2 ] not in visited :
50
+ visited .append ([start , 2 ])
51
+ answer += 1
52
+
53
+ return answer
54
+
55
+ print (solution ("LURDLLURD" ))
0 commit comments