< 이 글은 책 '이것이 취업을 위한 코딩 테스트다' 에서 발췌한 내용을 인용했습니다. >
게임 개발
<무지성 코드>
n, m = map(int, input().split())
x, y, d = map(int, input().split())
mm = [list(map(int, input().split())) for i in range(n)]
dx = [0, 1, 0, -1]
dy = [-1, 0, 1, 0]
count = 1
turn_count = 0
def left():
global d
if d == 0:
d = 3
else:
d -= 1
while True:
left()
turn_count += 1
nx = x + dx[d]
ny = y + dx[d]
if mm[nx][ny] == 0:
x = nx
y = ny
mm[x][y] = 2
count += 1
if turn_count == 4:
nx = x - dx[d]
ny = y - dy[d]
if mm[nx][ny] == 1:
break
else:
x, y = nx, ny
turn_count = 0
print(count)
< 답안 예시 >
n, m = map(int, input().split())
d = [[0] * m for _ in range(n)]
x, y, direction = map(int, input().split())
d[x][y] = 1
array = []
for i in range(n):
array.append(list(map(int, input().split())))
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
def turn_left():
global direction
direction -= 1
if direction == -1:
direction = 3
count = 1
turn_time = 0
while True:
turn_left()
nx = x + dx[direction]
ny = y + dy[direction]
if d[nx][ny] == 0 and array[nx][ny] == 0:
d[nx][ny] = 1
x = nx
y = ny
count += 1
turn_time = 0
continue
else:
turn_time += 1
if turn_time == 4:
nx = x - dx[direction]
ny = y - dy[direction]
if array[nx][ny] == 0:
x = nx
y = ny
else:
break
turn_time = 0
print(count)
주어진 하나의 테스트 케이스만 보고 내 풀이가 맞은 줄만 알았지만, 오산이었다.
먼저 x,y의 좌표를 생각할때 무의식적으로 가로가 x축, 세로가 y축으로 계산했는데 문제를 다시보니 전혀 아니었다.
cs에서는 row와 column의 기준이 다를 수 있다는걸 항상 염두해두자.
또한 내 풀이의 turn_count 계산도 틀렸다. 이동이 완료되면 초기화하고 아니면 1을 증가시켜야 했었다.
문제를 오랜만에 풀면 항상 많은 곳에서 실수를 범한다.
제발 꾸준히 해보자..
'이것이 취업을 위한 코딩테스트다 with 파이썬' 카테고리의 다른 글
Chapter 5-2 탐색 알고리즘 DFS/BFS (0) | 2022.12.20 |
---|---|
Chapter 5-1 DFS/BPS (0) | 2022.12.20 |
Chapter 04-2 왕실의 나이트 (0) | 2022.11.28 |
Chapter 04-1 아이디어를 코드로 바꾸는 구현 (0) | 2022.11.24 |
Chapter 03-4 1이 될 때까지 (0) | 2022.11.23 |