상세 컨텐츠

본문 제목

[이것이 코딩테스트다] 구현

알고리즘

by ~지우~ 2023. 2. 23. 11:29

본문

728x90

예제 4-1. 상하좌우

내풀이

n = int(input())
x = 1
y = 1
move = list(map(str, input().split()))

i = 0
for i in range(len(move)):
    if move[i] == 'R' and y < n:
        y+=1
    elif move[i] == 'L' and y > 1:
        y-=1
    elif move[i] == 'D' and x < n:
        x+=1
    elif move[i] == 'U' and x > 1:
        x-=1
    
print("{} {}".format(x, y))

 답안예시

# N을 입력받기
n = int(input())
x,y = 1,1
plans = input().split()

# L,R,U,D에 따른 이동 방향
dx = [0,0,-1,1]
dy = [-1,1,0,0]
move_types = ['L','R','U','D']

# 이동 계획을 하나씩 확인
for plan in plans:
	# 이동 후 좌표 구하기
    for i in range(len(move_types)):
        if plan == move_types[i]:
            nx = x + dx[i]
            ny = y + dy[i]
    # 공간을 벗어나는 경우 무시
    if nx < 1 or ny < 1 or nx > n or ny > n:
        continue
    # 이동 수행
    x,y = nx,ny

print(x,y)

 

 

 

예제 4-2. 시각

풀이

h = int(input())
cnt = 0

for i in range(h+1):
    for j in range(60):
        for k in range(60):
            if '3' in str(i)+str(j)+str(k):
                cnt+=1

print(cnt)

 

 

실전문제 4-3. 왕실의 나이트

풀이

# 현재 나이트의 위치 입력받기
current = input()

col = int(ord(current[0])) - int(ord('a')) + 1
row = int(current[1])
result = 0

# 나이트가 이동할 수 있는 8가지 방향 정의
move = [(-2, -1), (-2, 1), (2, -1), (2, 1), (-1, -2), (-1, 2), (1, 2), (1, -2)]
for i in move:
	# 이동하고자 하는 위치 확인
    row += i[0]
    col ++ i[1]
    # 해당 위치로 이동이 가능하다면 카운트 증가
    if row >= 1 and row <= 8 and col >= 1 and col <= 8:
        result += 1
        
print(result)

 

728x90

관련글 더보기

댓글 영역