문제요약
나의 코드 및 설명
- def find_distance(a,b,r,s):
동근이로부터 상점까지의 최소 거리를 찾는 메서드를 생성하였다. 동근이의 위치(a)가 어디냐에 따라, 상점의 위치(r)가 어디냐에 따라 거리 계산하는 법이 달라지므로, 제법 복잡하고 노가다 방법으로 코드를 작성하였다. - result : find_distance() 메서드가 실행될 때마다 나오는 값을 result 값에 저장한다.
- 입력받은 상점의 개수만큼 find_distance() 메서드를 실행시키고, result 값을 출력한다.
result = 0
def find_distance(a,b, r, s):
global n, m, result
if a == 1:
if r == 2:
result += min(b+m+s, (n-b)+m+(n-s))
elif r == 3:
result += b+s
elif r == 4:
result += n-b+s
elif r == 1:
result += abs(b-s)
elif a == 2:
if r == 1:
result += min(b+m+s, (n-b)+m+(n-s))
elif r == 3:
result += b+m-s
elif r == 4:
result += n-b+m-s
elif r == 2:
result += abs(b-s)
elif a == 3:
if r == 1:
result += b+s
elif r == 2:
result += m-b+s
elif r == 4:
result += min(b+n+s, (m-b)+n+(m-s))
elif r == 3:
result += abs(b-s)
elif a == 4:
if r == 1:
result += b+n-s
elif r == 2:
result += m-b+n-s
elif r == 3:
result += min(b+n+s, (m-b)+n+(m-s))
elif r == 4:
result += abs(b-s)
n, m = map(int, input().split())
how_many_store = int(input())
direction_list = []
distance_list = []
for i in range(how_many_store):
direction, distance = map(int, input().split())
direction_list.append(direction)
distance_list.append(distance)
dk_direction, dk_distance = map(int, input().split())
for i in range(how_many_store):
find_distance(dk_direction,dk_distance,direction_list[i],distance_list[i])
print(result)
다른 풀이 및 설명
- 동근이와 상점 사이의 상대 거리를 구하지 않고, (0,0)부터 동근이, 상점과의 절대 거리를 통해 문제를 풀이하는 방법이다.
- for _ in range(n+1) : 리스트 course의 제일 마지막에 동근이의 위치, 거리를 저장하기 위해 범위를 n이 아닌 n+1로 설정한다.
- in_course = abs(course[-1] - course[i]) : 사각형을 일자로 펴 본다고 생각했을 때 사이 거리는 뺀 값이다.
- out_course = 2 * (w + h) - in_course : 아웃코스는 사각형의 둘레에서 인코스를 뺀 값이다.
def get_distance(x, y):
if x == 1: #북
return y
if x == 2: #남
return w + h + w - y
if x == 3: #서
return w + h + w + h - y
if x == 4: #동
return w + y
w, h = map(int, input().split())
n = int(input())
course = []
for _ in range(n+1): # (0,0)에서 상점까지의 거리
x, y = map(int, input().split())
course.append(get_distance(x,y))
answer = 0
for i in range(n): #동근이 거리 : course[-1]
in_course = abs(course[-1] - course[i])
out_course = 2 * (w + h) - in_course
answer += min(in_course, out_course)
print(answer)
피드백
나는 각 케이스마다 나오는 거리를 일일이 메서드에 작성하였는데, 절대 거리를 계산해서 간단히 푸는 방법도 있었다. 문제를 푸는 것도 중요하지만 어떻게 하면 더 간략히 코드를 작성할 수 있을까 더 고민해보자.
'Baekjoon > IM Level' 카테고리의 다른 글
[백준] 12927 배수 스위치 (실버4) (2) | 2023.03.14 |
---|---|
[백준] 2635 수 이어가기 (실버5) (0) | 2023.03.13 |
[백준] 2628 종이자르기 (실버5) (0) | 2023.03.10 |
[백준] 1244 스위치 켜고 끄기 (실버4) (0) | 2023.03.10 |
[백준] 2578 빙고 (실버4) (0) | 2023.03.09 |