이것이 취업을 위한 코딩 테스트다 with 파이썬을 공부하면서 정리한 내용입니다.
4 4
1 1 0
1 1 1 1
1 0 0 1
1 1 0 1
1 1 1 1
3
dx
, dy
라는 별도의 리스트를 만들어 방향을 정하는 것이 효과적x
와 y
좌표에 각각 dx[0]
, dy[0]
만큼 더함. 즉, 현재 위치에서 만큼 이동하는 것global
키워드 사용# N, M을 공백으로 구분하여 입력받기
n, m = map(int, input().split())
# 방문한 위치를 저장하기 위한 맵을 생성하여 0으로 초기화
d = [[0] * m for _ in range(n)]
# 현재 캐릭터의 X 좌표, Y 좌표, 방향을 입력받기
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)
import sys
n, m = map(int, sys.stdin.readline().split())
a, b, d = map(int, sys.stdin.readline().split())
world_map = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
player_map = [[-1] * m for _ in range(n)]
# 방향별 움직임
steps = ((-1, 0), (0, 1), (1, 0), (0, -1))
player_map[a][b] = 0
count = 1
turn_time = 0
while True:
# 현재 방향을 기준으로 왼쪽 방향으로 회전
d = d - 1 if d > 0 else 3
na = a + steps[d][0]
nb = b + steps[d][1]
# 아직 가보지 않은 칸이면
if player_map[na][nb] == -1:
# 왼쪽으로 회전한 횟수 초기화
turn_time = 0
# 이동하려는 곳이 육지면
if world_map[na][nb] == 0:
# 캐릭터가 가진 지도에 해당 위치를 육지로 표시
player_map[na][nb] = 0
# 캐릭터를 해당 위치로 이동
a = na
b = nb
count += 1
# 이동하려는 곳이 바다면
else:
# 캐릭터가 가진 지도에 해당 위치를 바다로 표시
player_map[na][nb] = 1
# 가본 칸이면
else:
# 왼쪽으로 회전한 횟수 + 1
turn_time += 1
# 네 방향 모두 가보지 않았으면 다시 1단계로
if turn_time < 4:
continue
# 네 방향 모두 가봤다면
else:
na = a - steps[d][0]
nb = b - steps[d][1]
# 가본 방향의 수 초기화
turn_time = 0
# 이동하려는 곳이 육지면
if world_map[na][nb] == 0:
# 캐릭터를 해당 위치로 이동
a = na
b = nb
else:
break
print(count)