https://github.com/ndb796/python-for-coding-test
상,하,좌,우로 지도를 벗어나지 않고 이동하기
import sys
sys.stdin = open('../input.txt')
n = int(input())
orders = input().split()
# orders can be
# L, R, U, D
dx = (-1, 1, 0, 0)
dy = (0, 0, -1, 1)
order2idx = {
'L': 0,
'R': 1,
'U': 2,
'D': 3
}
x, y = 1, 1
for idx, order in enumerate(orders):
tmp_x = x + dx[order2idx[order]]
tmp_y = y + dy[order2idx[order]]
if tmp_x < 1 or tmp_x > n or tmp_y < 1 or tmp_y > n:
continue
x, y = tmp_x, tmp_y
# print(idx, ': ', x, y)
print(y, x)
# 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)
move type을 반복문으로 찾는 것과 딕셔너리로 받는 것의 차이가 있다.
어렵지 않은 문제라 가볍게 컷
시각에 '3'이 있는 지를 카운트
import time
import sys
# sys.stdin = open('../input.txt')
# 86400
# print(60 * 60 * 24)
n = int(input())
def check_three(s):
s = str(s)
if '3' in s:
return 1
return 0
current = time.time()
cnt = 0
for hour in range(n+1):
if check_three(hour):
cnt += 60 * 60
continue
for min in range(60):
if check_three(min):
cnt += 60
continue
for sec in range(60):
if check_three(sec):
cnt += 1
print(time.time() - current)
print(cnt)
# H를 입력받기
h = int(input())
count = 0
for i in range(h + 1):
for j in range(60):
for k in range(60):
# 매 시각 안에 '3'이 포함되어 있다면 카운트 증가
if '3' in str(i) + str(j) + str(k):
count += 1
print(count)
코드 길이가 차이가 난다.
참고 답안은 모든 시각에 대해서 3을 조사했지만 나는 시, 분 순으로 상위 단계에서 3이 있으면 넘어가는 식으로 구현했다.
바다와 땅으로 이뤄진 지도에서 캐릭터 움직이기
import time
import sys
sys.stdin = open('../input.txt')
N, M = map(int, input().split())
x, y, direction = map(int, input().split())
visited = [[0]*M for _ in range(N)]
arr = [list(map(int, input().split())) for _ in range(N)]
# forward step can be
# N, E, S, W
dx = (0, 1, 0, -1)
dy = (-1, 0, 1, 0)
# initial state
cnt = 1
rotate_cnt = 0
visited[y][x] = 1
while True:
direction -= 1
if direction == -1:
direction = 3
tmp_x = x + dx[direction]
tmp_y = y + dy[direction]
if visited[tmp_y][tmp_x] + arr[tmp_y][tmp_x] >= 1:
rotate_cnt += 1
if rotate_cnt >= 4:
rotate_cnt = 0
tmp_x = x - dx[direction]
tmp_y = y - dy[direction]
if arr[tmp_y][tmp_x] == 1:
break
else:
x -= dx[direction]
y -= dy[direction]
continue
continue
rotate_cnt = 0
x, y = tmp_x, tmp_y
visited[y][x] = 1
cnt += 1
# print(y, x)
print(cnt)
# 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)
참고 답안은 회전한 다음 이동할 수 있는 조건이 만족되면 이동하는 것을 먼저 확인했지만 나는 조건이 만족되지 않았을 경우를 먼저 확인했다.
어떤 조건에 대해 분기점을 가지는 것의 차이는 내 답안의 경우 연속 3분기가 존재하고 참고 답안은 최대 2분기이다. 분기를 어떻게 잡는냐가 구현 문제의 핵심이라고 생각하기 때문에 다음에 문제를 풀 때, 분기점에 집중해서 구현해봐야겠다.
그리고 위 문제와 같이 행, 열로 표기하는 matrix문제는 헷갈리는 면이 있다. x, y로 표기하는 것으로 통일하지만 순서를 바꿔야 하거나, 상승과 하강의 부호가 바뀔 수 있다는 것 생각해야 한다. 주의할 필요가 있다.