파이썬 알고리즘 279번 | [백준 8911번] 거북이 - 구현

Yunny.Log ·2022년 11월 27일
0

Algorithm

목록 보기
284/318
post-thumbnail

279. 거북이

1) 어떤 전략(알고리즘)으로 해결?

  • 구현

2) 코딩 설명

<내 풀이>


import sys
# F: 한 눈금 앞으로 /  B: 한 눈금 뒤로
# L: 왼쪽으로 90도 회전 / R: 오른쪽으로 90도 회전

dir = [
    # F(0)         B(1)
    [ [0, 1 ] ,  [0, -1] ], # 북 
    [ [1, 0 ] ,  [-1, 0] ], # 동
    [ [0, -1] ,  [ 0, 1] ], # 남
    [ [-1, 0] ,  [1,  0] ], # 서
]

t = int(sys.stdin.readline())

case = []
road = []
for i in range(t) : 
    case.append(list(sys.stdin.readline().strip()))

for i in range(t) :
    # 초기화 작업 - 북 (왼 ) 동 남 서 position
    pos = 0 
    # 현재 좌표 (r,c)
    disr = 0 
    disc = 0
    road=[(0,0)]
    
    for v in range(len(case[i])) : 
        if case[i][v] == 'F' :  # dir[pos][0]
            disr+=dir[pos][0][0]
            disc+=dir[pos][0][1]
        elif case[i][v] == 'B' : # dir[pos][1]
            disr+=dir[pos][1][0]
            disc+=dir[pos][1][1]
        elif case[i][v] == 'L' : 
            pos-=1
            if(pos<0) : 
                pos+=4
            pos%=4 # 0 1 2 3 중에서 하나이므로
        elif case[i][v] == 'R' : 
            pos+=1
            pos%=4 
        road.append((disr, disc))

    # ((가장 큰 x좌표)-(가장 작은 x좌표))
    #				*
    # ((가장 큰 y좌표)-(가장 작은 y좌표))
    # 가 넓이 
    
    width = max(road, key = lambda x:x[0])[0] 
    		- min(road, key = lambda x:x[0])[0]
            
    height = max(road, key = lambda x:x[1])[1] 
    		- min(road, key = lambda x:x[1])[1]
            
    print(width * height)

<다른 분의 풀이 >

출처 : 출처


n = int(input())

dx = [0,-1,0,1]
dy = [1,0,-1,0] # 북 서 남 동

for i in range(n):
    pos_x = 0
    pos_y = 0
    pos_dir = 0  # 0북 1서 2남 3동
    move = list(input())
    trace = [(pos_x, pos_y)]
    for j in move:
        if j == 'F':
            pos_x = pos_x + dx[pos_dir]
            pos_y = pos_y + dy[pos_dir]
        elif j == 'B':
            pos_x = pos_x - dx[pos_dir]
            pos_y = pos_y - dy[pos_dir]
        elif j == 'L':
            if pos_dir == 3:
                pos_dir = 0
            else:
                pos_dir += 1
        elif j == 'R':
            if pos_dir == 0:
                pos_dir = 3
            else:
                pos_dir -= 1

        trace.append((pos_x, pos_y))
    width = max(trace, key = lambda x:x[0])[0] - min(trace, key = lambda x:x[0])[0]
    height = max(trace, key = lambda x:x[1])[1] - min(trace, key = lambda x:x[1])[1]
    print(width * height)

내 풀이와 비교해서 내 풀이의 부족했던 점 !

  • 나는 모든 경우의 수를 이차원 배열로 해서 저장했었는데, 그럴 필요가 없었네!!!

<반성 점>

  • 넓이를 어떻게 구하지에 대한 생각이 부족했던 점
  • 구현을 좀 더 효율적이게 생각하지 못한 점

<배운 점>

넓이 : ((가장 큰 x좌표)-(가장 작은 x좌표))*((가장 큰 y좌표)-(가장 작은 y좌표))

람다 정렬 ,, 항상 까먹어

  • key 값을 기준으로 정렬을 해주는 것이지

width = max(road, key = lambda x:x[0])[0] - min(road, key = lambda x:x[0])[0]

height = max(road, key = lambda x:x[1])[1] - min(road, key = lambda x:x[1])[1]
print(width * height)

0개의 댓글