https://programmers.co.kr/learn/courses/30/lessons/49994
def solution(dirs):
count = 0
visited = set()
cy, cx = 0, 0
for i in range(len(dirs)):
ny, nx = get_next((cy, cx), dirs[i])
if -5 <= ny <= 5 and -5 <= nx <= 5:
if (cy, cx, ny, nx) not in visited and (ny, nx, cy, cx) not in visited:
visited.add((cy, cx, ny, nx))
count += 1
cy, cx = ny, nx
return count
def get_next(curr, d):
cy, cx = curr
if d == 'U':
return cy+1, cx
elif d == 'D':
return cy-1, cx
elif d == 'L':
return cy, cx-1
elif d == 'R':
return cy, cx+1
import java.util.HashSet;
class Solution {
HashSet<String> visited = new HashSet<>();
int count = 0;
int cy = 0, cx = 0;
public int solution(String dirs) {
for(int i=0; i<dirs.length(); i++){
int[] next = get_next(cy, cx, dirs.charAt(i));
int ny = next[0], nx = next[1];
if(-5<=ny && ny<=5 && -5<=nx && nx<=5){
if(!visited.contains(""+cy+cx+ny+nx) && !visited.contains(""+ny+nx+cy+cx)){
visited.add(""+cy+cx+ny+nx);
count += 1;
}
cy = ny; cx = nx;
}
}
return count;
}
int[] get_next(int cy, int cx, char d){
int[] next = {cy, cx};
if(d == 'U')
next[0] += 1;
else if(d == 'D')
next[0] -= 1;
else if(d == 'L')
next[1] -= 1;
else
next[1] += 1;
return next;
}
}