파이썬 알고리즘-98 (프로그래머스) 방문길이

10468 단어 algorithmalgorithm

코드

def solution(dirs):
    answer = 0
    dxy={'U':1,'D':-1,'R':1,'L':-1}
    cur_x,cur_y=0,0
    x,y=0,0
    passed=set()
    for dir in dirs:
      if -5<=cur_x<=5 and -5<=cur_y<=5:
        if (dir=='R' or dir=='L') and -5<=cur_x+dxy[dir]<=5:
          x=cur_x+dxy[dir]
        elif(dir=='U' or dir=='D') and -5<=cur_y+dxy[dir]<=5:
          y=cur_y+dxy[dir]
      if not (cur_x==x and cur_y==y):
        passed.add((cur_x,cur_y,x,y))
        cur_x,cur_y=x,y

    answer=len(passed)
    return answer

# 틀린 풀이

다른 사람의 풀이

def solution(dirs):
    answer = 0
    # 주어진 방향에 따라 (x,y)좌표를 설정
    dxy={'U':(0,1),'D':(0,-1),'R':(1,0),'L':(-1,0)}
    cur_x,cur_y=0,0
    x,y=0,0
    passed=set()
    for dir in dirs:
      x,y=cur_x+dxy[dir][0], cur_y+dxy[dir][1]
      if -5<=x<=5 and -5<=y<=5:
        passed.add((cur_x,cur_y,x,y))
        passed.add((x,y,cur_x,cur_y))
        cur_x, cur_y=x,y

    answer=len(passed)//2
    return answer

좋은 웹페이지 즐겨찾기