This repository was archived by the owner on Mar 18, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions CodeTree/메이즈 러너/jisu.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
"""
풀이 시작 : 2023-10-13 12:40 (이후 시간을 측정하지 않고 과제 느낌으로 풀이)
#### 제한사항
- 미로의 크기 : 4 <= N <= 10
- 참가자 수 : 1 <= M <= 10
- 게임 시간 : 1 <= K <= 100

#### 풀이
1. 이동
2. 회전
2-1. 정사각형 찾기
2-2. 회전시키기

풀이 완료 : 2023-10-14 18:03 (이틀동안 이거만 함 ㅎㅎ..)
수행시간 | 메모리
--|--
327ms | 27MB
"""

import sys
from typing import Tuple
from collections import deque

input = sys.stdin.readline

N, M, K = map(int, input().rstrip().split())

matrix = [list(map(int, input().rstrip().split())) for _ in range(N)]
participants = deque(
[tuple(map(lambda x: int(x) - 1, input().rstrip().split())) for _ in range(M)]
)
E = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))

dy = [-1, 1, 0, 0] # 상 하 좌 우 순서
dx = [0, 0, -1, 1]

answer = 0


def move(py: int, px: int) -> int:
"""
특정 참가자를 출구와 가까운 쪽으로 1만큼 이동시킨다.
이동 시 출구와 가까워지는 쪽으로, 상-하-좌-우 우선순위로 이동한다.

input : 이동시킬 참가자 (y, x) 좌표
output : 참가자 이동 여부 (이동했으면 1, 이동하지 않았으면 0)
"""
# 기존 참가자와 출구까지의 최단 거리
dist = abs(py - E[0]) + abs(px - E[1])

for d in range(4):
ny = py + dy[d]
nx = px + dx[d]
# 이동 후 참가자와 출구까지의 최단 거리
new_dist = abs(ny - E[0]) + abs(nx - E[1])
# 이동 가능하며, 출구와 가까워지는 경우
if 0 <= ny < N and 0 <= nx < N and matrix[ny][nx] == 0 and new_dist < dist:
# 이동 후 좌표가 탈출구인 경우 탈출시키고 아닌 경우, 이동시킨 좌표를 큐에 삽입
if (ny, nx) != E:
participants.append((ny, nx))
# 이동 성공 시 count 1 반환
return 1
# 이동 실패 시 원래 좌표를 다시 큐에 삽입, count 0 반환
participants.append((py, px))

return 0


def get_rectangle() -> Tuple[int, int, int, int]:
"""
출구와 최소 한 명의 참가자를 포함하는 최소 넓이 직사각형의 네 좌표를 반환한다.

input : x
output : 직사각형의 min_y, min_x, max_y, max_x
"""
rectangles = []

for y, x in set(participants):
max_y = max(y, E[0])
min_y = min(y, E[0])
max_x = max(x, E[1])
min_x = min(x, E[1])

# 한 변의 길이
side_len = max(max_y - min_y, max_x - min_x)
# 한 변의 길이를 유지하는 최소의 좌상단 좌표를 가지는 직사각형 좌표 구하기
min_y = max(max_y - side_len, 0)
max_y = min_y + side_len
min_x = max(max_x - side_len, 0)
max_x = min_x + side_len

rectangles.append((side_len**2, min_y, min_x, max_y, max_x))
# 우선순위 : 넓이 > 좌상단 y좌표 > 좌상단 x좌표
return min(rectangles)[1:]


def rotate(min_y: int, min_x: int, max_y: int, max_x: int) -> None:
"""
rotate시킬 정사각형의 좌표를 받아 시계방향으로 90도 회전시킨다.

input : rotate 시킬 정사각형의 min_y, min_x, max_y, max_x 좌표
output : x
"""
global E

participants_set = set(participants)
# rotate 시킬 부분의 임시 matrix
rotate_matrix = [
[0 for _ in range(min_x, max_x + 1)] for _ in range(min_y, max_y + 1)
]

# rotate전 정보 백업
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 벽의 경우 내구도 -1 시켜 백업
if matrix[y][x] > 0:
rotate_matrix[y - min_y][x - min_x] = matrix[y][x] - 1
# 출구 좌표 정보 백업
elif (y, x) == E:
rotate_matrix[y - min_y][x - min_x] = "E"
# 참가자 좌표 정보 백업
elif (y, x) in participants_set:
# 참가자는 동일 좌표에 여러명이 위치할 수 있음
cnt = 0
while (y, x) in participants:
cnt += 1
participants.remove((y, x))
# 참가자 한 명당 *의 개수로 백업
rotate_matrix[y - min_y][x - min_x] = "*" * cnt

# 해당 백업 matrix 90도 회전
rotate_matrix = [list(row)[::-1] for row in zip(*rotate_matrix)]

# 원본 matrix의 정사각형 위치를 90도 회전시킨 백업 matrix로 대치
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 회전 후 참가자 위치를 다시 큐에 삽입
if str(rotate_matrix[y - min_y][x - min_x]).startswith("*"):
# 기존 존재하던 참가자 수만큼 삽입
for _ in range(len(rotate_matrix[y - min_y][x - min_x])):
participants.append((y, x))
matrix[y][x] = 0
# 회전 후 출구 위치
elif rotate_matrix[y - min_y][x - min_x] == "E":
E = (y, x)
matrix[y][x] = 0
# 회전 후 벽의 내구도
else:
matrix[y][x] = rotate_matrix[y - min_y][x - min_x]


# 최대 k초 이동 가능
for i in range(K):
# 참가자 당 한 번씩 move
M = len(participants)
for _ in range(M):
answer += move(*participants.popleft())
# 이동 과정에서 참가자가 모두 탈출한 경우 종료
if not participants:
break
# 정사각형 좌표를 구해 해당 위치 90도 rotate
rotate(*get_rectangle())

print(answer)
print(E[0] + 1, E[1] + 1)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions CodeTree/메이즈 러너/jisu.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
"""
풀이 시작 : 2023-10-13 12:40 (이후 시간을 측정하지 않고 과제 느낌으로 풀이)
#### 제한사항
- 미로의 크기 : 4 <= N <= 10
- 참가자 수 : 1 <= M <= 10
- 게임 시간 : 1 <= K <= 100

#### 풀이
1. 이동
2. 회전
2-1. 정사각형 찾기
2-2. 회전시키기

풀이 완료 : 2023-10-14 18:03 (이틀동안 이거만 함 ㅎㅎ..)
수행시간 | 메모리
--|--
327ms | 27MB
"""

import sys
from typing import Tuple
from collections import deque

input = sys.stdin.readline

N, M, K = map(int, input().rstrip().split())

matrix = [list(map(int, input().rstrip().split())) for _ in range(N)]
participants = deque(
[tuple(map(lambda x: int(x) - 1, input().rstrip().split())) for _ in range(M)]
)
E = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))

dy = [-1, 1, 0, 0] # 상 하 좌 우 순서
dx = [0, 0, -1, 1]

answer = 0


def move(py: int, px: int) -> int:
"""
특정 참가자를 출구와 가까운 쪽으로 1만큼 이동시킨다.
이동 시 출구와 가까워지는 쪽으로, 상-하-좌-우 우선순위로 이동한다.

input : 이동시킬 참가자 (y, x) 좌표
output : 참가자 이동 여부 (이동했으면 1, 이동하지 않았으면 0)
"""
# 기존 참가자와 출구까지의 최단 거리
dist = abs(py - E[0]) + abs(px - E[1])

for d in range(4):
ny = py + dy[d]
nx = px + dx[d]
# 이동 후 참가자와 출구까지의 최단 거리
new_dist = abs(ny - E[0]) + abs(nx - E[1])
# 이동 가능하며, 출구와 가까워지는 경우
if 0 <= ny < N and 0 <= nx < N and matrix[ny][nx] == 0 and new_dist < dist:
# 이동 후 좌표가 탈출구인 경우 탈출시키고 아닌 경우, 이동시킨 좌표를 큐에 삽입
if (ny, nx) != E:
participants.append((ny, nx))
# 이동 성공 시 count 1 반환
return 1
# 이동 실패 시 원래 좌표를 다시 큐에 삽입, count 0 반환
participants.append((py, px))

return 0


def get_rectangle() -> Tuple[int, int, int, int]:
"""
출구와 최소 한 명의 참가자를 포함하는 최소 넓이 직사각형의 네 좌표를 반환한다.

input : x
output : 직사각형의 min_y, min_x, max_y, max_x
"""
rectangles = []

for y, x in set(participants):
max_y = max(y, E[0])
min_y = min(y, E[0])
max_x = max(x, E[1])
min_x = min(x, E[1])

# 한 변의 길이
side_len = max(max_y - min_y, max_x - min_x)
# 한 변의 길이를 유지하는 최소의 좌상단 좌표를 가지는 직사각형 좌표 구하기
min_y = max(max_y - side_len, 0)
max_y = min_y + side_len
min_x = max(max_x - side_len, 0)
max_x = min_x + side_len

rectangles.append((side_len**2, min_y, min_x, max_y, max_x))
# 우선순위 : 넓이 > 좌상단 y좌표 > 좌상단 x좌표
return min(rectangles)[1:]


def rotate(min_y: int, min_x: int, max_y: int, max_x: int) -> None:
"""
rotate시킬 정사각형의 좌표를 받아 시계방향으로 90도 회전시킨다.

input : rotate 시킬 정사각형의 min_y, min_x, max_y, max_x 좌표
output : x
"""
global E

participants_set = set(participants)
# rotate 시킬 부분의 임시 matrix
rotate_matrix = [
[0 for _ in range(min_x, max_x + 1)] for _ in range(min_y, max_y + 1)
]

# rotate전 정보 백업
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 벽의 경우 내구도 -1 시켜 백업
if matrix[y][x] > 0:
rotate_matrix[y - min_y][x - min_x] = matrix[y][x] - 1
# 출구 좌표 정보 백업
elif (y, x) == E:
rotate_matrix[y - min_y][x - min_x] = "E"
# 참가자 좌표 정보 백업
elif (y, x) in participants_set:
# 참가자는 동일 좌표에 여러명이 위치할 수 있음
cnt = 0
while (y, x) in participants:
cnt += 1
participants.remove((y, x))
# 참가자 한 명당 *의 개수로 백업
rotate_matrix[y - min_y][x - min_x] = "*" * cnt

# 해당 백업 matrix 90도 회전
rotate_matrix = [list(row)[::-1] for row in zip(*rotate_matrix)]

# 원본 matrix의 정사각형 위치를 90도 회전시킨 백업 matrix로 대치
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 회전 후 참가자 위치를 다시 큐에 삽입
if str(rotate_matrix[y - min_y][x - min_x]).startswith("*"):
# 기존 존재하던 참가자 수만큼 삽입
for _ in range(len(rotate_matrix[y - min_y][x - min_x])):
participants.append((y, x))
matrix[y][x] = 0
# 회전 후 출구 위치
elif rotate_matrix[y - min_y][x - min_x] == "E":
E = (y, x)
matrix[y][x] = 0
# 회전 후 벽의 내구도
else:
matrix[y][x] = rotate_matrix[y - min_y][x - min_x]


# 최대 k초 이동 가능
for i in range(K):
# 참가자 당 한 번씩 move
M = len(participants)
for _ in range(M):
answer += move(*participants.popleft())
# 이동 과정에서 참가자가 모두 탈출한 경우 종료
if not participants:
break
# 정사각형 좌표를 구해 해당 위치 90도 rotate
rotate(*get_rectangle())

print(answer)
print(E[0] + 1, E[1] + 1)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions CodeTree/메이즈 러너/jisu.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
"""
풀이 시작 : 2023-10-13 12:40 (이후 시간을 측정하지 않고 과제 느낌으로 풀이)
#### 제한사항
- 미로의 크기 : 4 <= N <= 10
- 참가자 수 : 1 <= M <= 10
- 게임 시간 : 1 <= K <= 100

#### 풀이
1. 이동
2. 회전
2-1. 정사각형 찾기
2-2. 회전시키기

풀이 완료 : 2023-10-14 18:03 (이틀동안 이거만 함 ㅎㅎ..)
수행시간 | 메모리
--|--
327ms | 27MB
"""

import sys
from typing import Tuple
from collections import deque

input = sys.stdin.readline

N, M, K = map(int, input().rstrip().split())

matrix = [list(map(int, input().rstrip().split())) for _ in range(N)]
participants = deque(
[tuple(map(lambda x: int(x) - 1, input().rstrip().split())) for _ in range(M)]
)
E = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))

dy = [-1, 1, 0, 0] # 상 하 좌 우 순서
dx = [0, 0, -1, 1]

answer = 0


def move(py: int, px: int) -> int:
"""
특정 참가자를 출구와 가까운 쪽으로 1만큼 이동시킨다.
이동 시 출구와 가까워지는 쪽으로, 상-하-좌-우 우선순위로 이동한다.

input : 이동시킬 참가자 (y, x) 좌표
output : 참가자 이동 여부 (이동했으면 1, 이동하지 않았으면 0)
"""
# 기존 참가자와 출구까지의 최단 거리
dist = abs(py - E[0]) + abs(px - E[1])

for d in range(4):
ny = py + dy[d]
nx = px + dx[d]
# 이동 후 참가자와 출구까지의 최단 거리
new_dist = abs(ny - E[0]) + abs(nx - E[1])
# 이동 가능하며, 출구와 가까워지는 경우
if 0 <= ny < N and 0 <= nx < N and matrix[ny][nx] == 0 and new_dist < dist:
# 이동 후 좌표가 탈출구인 경우 탈출시키고 아닌 경우, 이동시킨 좌표를 큐에 삽입
if (ny, nx) != E:
participants.append((ny, nx))
# 이동 성공 시 count 1 반환
return 1
# 이동 실패 시 원래 좌표를 다시 큐에 삽입, count 0 반환
participants.append((py, px))

return 0


def get_rectangle() -> Tuple[int, int, int, int]:
"""
출구와 최소 한 명의 참가자를 포함하는 최소 넓이 직사각형의 네 좌표를 반환한다.

input : x
output : 직사각형의 min_y, min_x, max_y, max_x
"""
rectangles = []

for y, x in set(participants):
max_y = max(y, E[0])
min_y = min(y, E[0])
max_x = max(x, E[1])
min_x = min(x, E[1])

# 한 변의 길이
side_len = max(max_y - min_y, max_x - min_x)
# 한 변의 길이를 유지하는 최소의 좌상단 좌표를 가지는 직사각형 좌표 구하기
min_y = max(max_y - side_len, 0)
max_y = min_y + side_len
min_x = max(max_x - side_len, 0)
max_x = min_x + side_len

rectangles.append((side_len**2, min_y, min_x, max_y, max_x))
# 우선순위 : 넓이 > 좌상단 y좌표 > 좌상단 x좌표
return min(rectangles)[1:]


def rotate(min_y: int, min_x: int, max_y: int, max_x: int) -> None:
"""
rotate시킬 정사각형의 좌표를 받아 시계방향으로 90도 회전시킨다.

input : rotate 시킬 정사각형의 min_y, min_x, max_y, max_x 좌표
output : x
"""
global E

participants_set = set(participants)
# rotate 시킬 부분의 임시 matrix
rotate_matrix = [
[0 for _ in range(min_x, max_x + 1)] for _ in range(min_y, max_y + 1)
]

# rotate전 정보 백업
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 벽의 경우 내구도 -1 시켜 백업
if matrix[y][x] > 0:
rotate_matrix[y - min_y][x - min_x] = matrix[y][x] - 1
# 출구 좌표 정보 백업
elif (y, x) == E:
rotate_matrix[y - min_y][x - min_x] = "E"
# 참가자 좌표 정보 백업
elif (y, x) in participants_set:
# 참가자는 동일 좌표에 여러명이 위치할 수 있음
cnt = 0
while (y, x) in participants:
cnt += 1
participants.remove((y, x))
# 참가자 한 명당 *의 개수로 백업
rotate_matrix[y - min_y][x - min_x] = "*" * cnt

# 해당 백업 matrix 90도 회전
rotate_matrix = [list(row)[::-1] for row in zip(*rotate_matrix)]

# 원본 matrix의 정사각형 위치를 90도 회전시킨 백업 matrix로 대치
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 회전 후 참가자 위치를 다시 큐에 삽입
if str(rotate_matrix[y - min_y][x - min_x]).startswith("*"):
# 기존 존재하던 참가자 수만큼 삽입
for _ in range(len(rotate_matrix[y - min_y][x - min_x])):
participants.append((y, x))
matrix[y][x] = 0
# 회전 후 출구 위치
elif rotate_matrix[y - min_y][x - min_x] == "E":
E = (y, x)
matrix[y][x] = 0
# 회전 후 벽의 내구도
else:
matrix[y][x] = rotate_matrix[y - min_y][x - min_x]


# 최대 k초 이동 가능
for i in range(K):
# 참가자 당 한 번씩 move
M = len(participants)
for _ in range(M):
answer += move(*participants.popleft())
# 이동 과정에서 참가자가 모두 탈출한 경우 종료
if not participants:
break
# 정사각형 좌표를 구해 해당 위치 90도 rotate
rotate(*get_rectangle())

print(answer)
print(E[0] + 1, E[1] + 1)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions CodeTree/메이즈 러너/jisu.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
"""
풀이 시작 : 2023-10-13 12:40 (이후 시간을 측정하지 않고 과제 느낌으로 풀이)
#### 제한사항
- 미로의 크기 : 4 <= N <= 10
- 참가자 수 : 1 <= M <= 10
- 게임 시간 : 1 <= K <= 100

#### 풀이
1. 이동
2. 회전
2-1. 정사각형 찾기
2-2. 회전시키기

풀이 완료 : 2023-10-14 18:03 (이틀동안 이거만 함 ㅎㅎ..)
수행시간 | 메모리
--|--
327ms | 27MB
"""

import sys
from typing import Tuple
from collections import deque

input = sys.stdin.readline

N, M, K = map(int, input().rstrip().split())

matrix = [list(map(int, input().rstrip().split())) for _ in range(N)]
participants = deque(
[tuple(map(lambda x: int(x) - 1, input().rstrip().split())) for _ in range(M)]
)
E = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))

dy = [-1, 1, 0, 0] # 상 하 좌 우 순서
dx = [0, 0, -1, 1]

answer = 0


def move(py: int, px: int) -> int:
"""
특정 참가자를 출구와 가까운 쪽으로 1만큼 이동시킨다.
이동 시 출구와 가까워지는 쪽으로, 상-하-좌-우 우선순위로 이동한다.

input : 이동시킬 참가자 (y, x) 좌표
output : 참가자 이동 여부 (이동했으면 1, 이동하지 않았으면 0)
"""
# 기존 참가자와 출구까지의 최단 거리
dist = abs(py - E[0]) + abs(px - E[1])

for d in range(4):
ny = py + dy[d]
nx = px + dx[d]
# 이동 후 참가자와 출구까지의 최단 거리
new_dist = abs(ny - E[0]) + abs(nx - E[1])
# 이동 가능하며, 출구와 가까워지는 경우
if 0 <= ny < N and 0 <= nx < N and matrix[ny][nx] == 0 and new_dist < dist:
# 이동 후 좌표가 탈출구인 경우 탈출시키고 아닌 경우, 이동시킨 좌표를 큐에 삽입
if (ny, nx) != E:
participants.append((ny, nx))
# 이동 성공 시 count 1 반환
return 1
# 이동 실패 시 원래 좌표를 다시 큐에 삽입, count 0 반환
participants.append((py, px))

return 0


def get_rectangle() -> Tuple[int, int, int, int]:
"""
출구와 최소 한 명의 참가자를 포함하는 최소 넓이 직사각형의 네 좌표를 반환한다.

input : x
output : 직사각형의 min_y, min_x, max_y, max_x
"""
rectangles = []

for y, x in set(participants):
max_y = max(y, E[0])
min_y = min(y, E[0])
max_x = max(x, E[1])
min_x = min(x, E[1])

# 한 변의 길이
side_len = max(max_y - min_y, max_x - min_x)
# 한 변의 길이를 유지하는 최소의 좌상단 좌표를 가지는 직사각형 좌표 구하기
min_y = max(max_y - side_len, 0)
max_y = min_y + side_len
min_x = max(max_x - side_len, 0)
max_x = min_x + side_len

rectangles.append((side_len**2, min_y, min_x, max_y, max_x))
# 우선순위 : 넓이 > 좌상단 y좌표 > 좌상단 x좌표
return min(rectangles)[1:]


def rotate(min_y: int, min_x: int, max_y: int, max_x: int) -> None:
"""
rotate시킬 정사각형의 좌표를 받아 시계방향으로 90도 회전시킨다.

input : rotate 시킬 정사각형의 min_y, min_x, max_y, max_x 좌표
output : x
"""
global E

participants_set = set(participants)
# rotate 시킬 부분의 임시 matrix
rotate_matrix = [
[0 for _ in range(min_x, max_x + 1)] for _ in range(min_y, max_y + 1)
]

# rotate전 정보 백업
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 벽의 경우 내구도 -1 시켜 백업
if matrix[y][x] > 0:
rotate_matrix[y - min_y][x - min_x] = matrix[y][x] - 1
# 출구 좌표 정보 백업
elif (y, x) == E:
rotate_matrix[y - min_y][x - min_x] = "E"
# 참가자 좌표 정보 백업
elif (y, x) in participants_set:
# 참가자는 동일 좌표에 여러명이 위치할 수 있음
cnt = 0
while (y, x) in participants:
cnt += 1
participants.remove((y, x))
# 참가자 한 명당 *의 개수로 백업
rotate_matrix[y - min_y][x - min_x] = "*" * cnt

# 해당 백업 matrix 90도 회전
rotate_matrix = [list(row)[::-1] for row in zip(*rotate_matrix)]

# 원본 matrix의 정사각형 위치를 90도 회전시킨 백업 matrix로 대치
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 회전 후 참가자 위치를 다시 큐에 삽입
if str(rotate_matrix[y - min_y][x - min_x]).startswith("*"):
# 기존 존재하던 참가자 수만큼 삽입
for _ in range(len(rotate_matrix[y - min_y][x - min_x])):
participants.append((y, x))
matrix[y][x] = 0
# 회전 후 출구 위치
elif rotate_matrix[y - min_y][x - min_x] == "E":
E = (y, x)
matrix[y][x] = 0
# 회전 후 벽의 내구도
else:
matrix[y][x] = rotate_matrix[y - min_y][x - min_x]


# 최대 k초 이동 가능
for i in range(K):
# 참가자 당 한 번씩 move
M = len(participants)
for _ in range(M):
answer += move(*participants.popleft())
# 이동 과정에서 참가자가 모두 탈출한 경우 종료
if not participants:
break
# 정사각형 좌표를 구해 해당 위치 90도 rotate
rotate(*get_rectangle())

print(answer)
print(E[0] + 1, E[1] + 1)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions CodeTree/메이즈 러너/jisu.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
"""
풀이 시작 : 2023-10-13 12:40 (이후 시간을 측정하지 않고 과제 느낌으로 풀이)
#### 제한사항
- 미로의 크기 : 4 <= N <= 10
- 참가자 수 : 1 <= M <= 10
- 게임 시간 : 1 <= K <= 100

#### 풀이
1. 이동
2. 회전
2-1. 정사각형 찾기
2-2. 회전시키기

풀이 완료 : 2023-10-14 18:03 (이틀동안 이거만 함 ㅎㅎ..)
수행시간 | 메모리
--|--
327ms | 27MB
"""

import sys
from typing import Tuple
from collections import deque

input = sys.stdin.readline

N, M, K = map(int, input().rstrip().split())

matrix = [list(map(int, input().rstrip().split())) for _ in range(N)]
participants = deque(
[tuple(map(lambda x: int(x) - 1, input().rstrip().split())) for _ in range(M)]
)
E = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))

dy = [-1, 1, 0, 0] # 상 하 좌 우 순서
dx = [0, 0, -1, 1]

answer = 0


def move(py: int, px: int) -> int:
"""
특정 참가자를 출구와 가까운 쪽으로 1만큼 이동시킨다.
이동 시 출구와 가까워지는 쪽으로, 상-하-좌-우 우선순위로 이동한다.

input : 이동시킬 참가자 (y, x) 좌표
output : 참가자 이동 여부 (이동했으면 1, 이동하지 않았으면 0)
"""
# 기존 참가자와 출구까지의 최단 거리
dist = abs(py - E[0]) + abs(px - E[1])

for d in range(4):
ny = py + dy[d]
nx = px + dx[d]
# 이동 후 참가자와 출구까지의 최단 거리
new_dist = abs(ny - E[0]) + abs(nx - E[1])
# 이동 가능하며, 출구와 가까워지는 경우
if 0 <= ny < N and 0 <= nx < N and matrix[ny][nx] == 0 and new_dist < dist:
# 이동 후 좌표가 탈출구인 경우 탈출시키고 아닌 경우, 이동시킨 좌표를 큐에 삽입
if (ny, nx) != E:
participants.append((ny, nx))
# 이동 성공 시 count 1 반환
return 1
# 이동 실패 시 원래 좌표를 다시 큐에 삽입, count 0 반환
participants.append((py, px))

return 0


def get_rectangle() -> Tuple[int, int, int, int]:
"""
출구와 최소 한 명의 참가자를 포함하는 최소 넓이 직사각형의 네 좌표를 반환한다.

input : x
output : 직사각형의 min_y, min_x, max_y, max_x
"""
rectangles = []

for y, x in set(participants):
max_y = max(y, E[0])
min_y = min(y, E[0])
max_x = max(x, E[1])
min_x = min(x, E[1])

# 한 변의 길이
side_len = max(max_y - min_y, max_x - min_x)
# 한 변의 길이를 유지하는 최소의 좌상단 좌표를 가지는 직사각형 좌표 구하기
min_y = max(max_y - side_len, 0)
max_y = min_y + side_len
min_x = max(max_x - side_len, 0)
max_x = min_x + side_len

rectangles.append((side_len**2, min_y, min_x, max_y, max_x))
# 우선순위 : 넓이 > 좌상단 y좌표 > 좌상단 x좌표
return min(rectangles)[1:]


def rotate(min_y: int, min_x: int, max_y: int, max_x: int) -> None:
"""
rotate시킬 정사각형의 좌표를 받아 시계방향으로 90도 회전시킨다.

input : rotate 시킬 정사각형의 min_y, min_x, max_y, max_x 좌표
output : x
"""
global E

participants_set = set(participants)
# rotate 시킬 부분의 임시 matrix
rotate_matrix = [
[0 for _ in range(min_x, max_x + 1)] for _ in range(min_y, max_y + 1)
]

# rotate전 정보 백업
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 벽의 경우 내구도 -1 시켜 백업
if matrix[y][x] > 0:
rotate_matrix[y - min_y][x - min_x] = matrix[y][x] - 1
# 출구 좌표 정보 백업
elif (y, x) == E:
rotate_matrix[y - min_y][x - min_x] = "E"
# 참가자 좌표 정보 백업
elif (y, x) in participants_set:
# 참가자는 동일 좌표에 여러명이 위치할 수 있음
cnt = 0
while (y, x) in participants:
cnt += 1
participants.remove((y, x))
# 참가자 한 명당 *의 개수로 백업
rotate_matrix[y - min_y][x - min_x] = "*" * cnt

# 해당 백업 matrix 90도 회전
rotate_matrix = [list(row)[::-1] for row in zip(*rotate_matrix)]

# 원본 matrix의 정사각형 위치를 90도 회전시킨 백업 matrix로 대치
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 회전 후 참가자 위치를 다시 큐에 삽입
if str(rotate_matrix[y - min_y][x - min_x]).startswith("*"):
# 기존 존재하던 참가자 수만큼 삽입
for _ in range(len(rotate_matrix[y - min_y][x - min_x])):
participants.append((y, x))
matrix[y][x] = 0
# 회전 후 출구 위치
elif rotate_matrix[y - min_y][x - min_x] == "E":
E = (y, x)
matrix[y][x] = 0
# 회전 후 벽의 내구도
else:
matrix[y][x] = rotate_matrix[y - min_y][x - min_x]


# 최대 k초 이동 가능
for i in range(K):
# 참가자 당 한 번씩 move
M = len(participants)
for _ in range(M):
answer += move(*participants.popleft())
# 이동 과정에서 참가자가 모두 탈출한 경우 종료
if not participants:
break
# 정사각형 좌표를 구해 해당 위치 90도 rotate
rotate(*get_rectangle())

print(answer)
print(E[0] + 1, E[1] + 1)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions CodeTree/메이즈 러너/jisu.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
"""
풀이 시작 : 2023-10-13 12:40 (이후 시간을 측정하지 않고 과제 느낌으로 풀이)
#### 제한사항
- 미로의 크기 : 4 <= N <= 10
- 참가자 수 : 1 <= M <= 10
- 게임 시간 : 1 <= K <= 100

#### 풀이
1. 이동
2. 회전
2-1. 정사각형 찾기
2-2. 회전시키기

풀이 완료 : 2023-10-14 18:03 (이틀동안 이거만 함 ㅎㅎ..)
수행시간 | 메모리
--|--
327ms | 27MB
"""

import sys
from typing import Tuple
from collections import deque

input = sys.stdin.readline

N, M, K = map(int, input().rstrip().split())

matrix = [list(map(int, input().rstrip().split())) for _ in range(N)]
participants = deque(
[tuple(map(lambda x: int(x) - 1, input().rstrip().split())) for _ in range(M)]
)
E = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))

dy = [-1, 1, 0, 0] # 상 하 좌 우 순서
dx = [0, 0, -1, 1]

answer = 0


def move(py: int, px: int) -> int:
"""
특정 참가자를 출구와 가까운 쪽으로 1만큼 이동시킨다.
이동 시 출구와 가까워지는 쪽으로, 상-하-좌-우 우선순위로 이동한다.

input : 이동시킬 참가자 (y, x) 좌표
output : 참가자 이동 여부 (이동했으면 1, 이동하지 않았으면 0)
"""
# 기존 참가자와 출구까지의 최단 거리
dist = abs(py - E[0]) + abs(px - E[1])

for d in range(4):
ny = py + dy[d]
nx = px + dx[d]
# 이동 후 참가자와 출구까지의 최단 거리
new_dist = abs(ny - E[0]) + abs(nx - E[1])
# 이동 가능하며, 출구와 가까워지는 경우
if 0 <= ny < N and 0 <= nx < N and matrix[ny][nx] == 0 and new_dist < dist:
# 이동 후 좌표가 탈출구인 경우 탈출시키고 아닌 경우, 이동시킨 좌표를 큐에 삽입
if (ny, nx) != E:
participants.append((ny, nx))
# 이동 성공 시 count 1 반환
return 1
# 이동 실패 시 원래 좌표를 다시 큐에 삽입, count 0 반환
participants.append((py, px))

return 0


def get_rectangle() -> Tuple[int, int, int, int]:
"""
출구와 최소 한 명의 참가자를 포함하는 최소 넓이 직사각형의 네 좌표를 반환한다.

input : x
output : 직사각형의 min_y, min_x, max_y, max_x
"""
rectangles = []

for y, x in set(participants):
max_y = max(y, E[0])
min_y = min(y, E[0])
max_x = max(x, E[1])
min_x = min(x, E[1])

# 한 변의 길이
side_len = max(max_y - min_y, max_x - min_x)
# 한 변의 길이를 유지하는 최소의 좌상단 좌표를 가지는 직사각형 좌표 구하기
min_y = max(max_y - side_len, 0)
max_y = min_y + side_len
min_x = max(max_x - side_len, 0)
max_x = min_x + side_len

rectangles.append((side_len**2, min_y, min_x, max_y, max_x))
# 우선순위 : 넓이 > 좌상단 y좌표 > 좌상단 x좌표
return min(rectangles)[1:]


def rotate(min_y: int, min_x: int, max_y: int, max_x: int) -> None:
"""
rotate시킬 정사각형의 좌표를 받아 시계방향으로 90도 회전시킨다.

input : rotate 시킬 정사각형의 min_y, min_x, max_y, max_x 좌표
output : x
"""
global E

participants_set = set(participants)
# rotate 시킬 부분의 임시 matrix
rotate_matrix = [
[0 for _ in range(min_x, max_x + 1)] for _ in range(min_y, max_y + 1)
]

# rotate전 정보 백업
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 벽의 경우 내구도 -1 시켜 백업
if matrix[y][x] > 0:
rotate_matrix[y - min_y][x - min_x] = matrix[y][x] - 1
# 출구 좌표 정보 백업
elif (y, x) == E:
rotate_matrix[y - min_y][x - min_x] = "E"
# 참가자 좌표 정보 백업
elif (y, x) in participants_set:
# 참가자는 동일 좌표에 여러명이 위치할 수 있음
cnt = 0
while (y, x) in participants:
cnt += 1
participants.remove((y, x))
# 참가자 한 명당 *의 개수로 백업
rotate_matrix[y - min_y][x - min_x] = "*" * cnt

# 해당 백업 matrix 90도 회전
rotate_matrix = [list(row)[::-1] for row in zip(*rotate_matrix)]

# 원본 matrix의 정사각형 위치를 90도 회전시킨 백업 matrix로 대치
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 회전 후 참가자 위치를 다시 큐에 삽입
if str(rotate_matrix[y - min_y][x - min_x]).startswith("*"):
# 기존 존재하던 참가자 수만큼 삽입
for _ in range(len(rotate_matrix[y - min_y][x - min_x])):
participants.append((y, x))
matrix[y][x] = 0
# 회전 후 출구 위치
elif rotate_matrix[y - min_y][x - min_x] == "E":
E = (y, x)
matrix[y][x] = 0
# 회전 후 벽의 내구도
else:
matrix[y][x] = rotate_matrix[y - min_y][x - min_x]


# 최대 k초 이동 가능
for i in range(K):
# 참가자 당 한 번씩 move
M = len(participants)
for _ in range(M):
answer += move(*participants.popleft())
# 이동 과정에서 참가자가 모두 탈출한 경우 종료
if not participants:
break
# 정사각형 좌표를 구해 해당 위치 90도 rotate
rotate(*get_rectangle())

print(answer)
print(E[0] + 1, E[1] + 1)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions CodeTree/메이즈 러너/jisu.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
"""
풀이 시작 : 2023-10-13 12:40 (이후 시간을 측정하지 않고 과제 느낌으로 풀이)
#### 제한사항
- 미로의 크기 : 4 <= N <= 10
- 참가자 수 : 1 <= M <= 10
- 게임 시간 : 1 <= K <= 100

#### 풀이
1. 이동
2. 회전
2-1. 정사각형 찾기
2-2. 회전시키기

풀이 완료 : 2023-10-14 18:03 (이틀동안 이거만 함 ㅎㅎ..)
수행시간 | 메모리
--|--
327ms | 27MB
"""

import sys
from typing import Tuple
from collections import deque

input = sys.stdin.readline

N, M, K = map(int, input().rstrip().split())

matrix = [list(map(int, input().rstrip().split())) for _ in range(N)]
participants = deque(
[tuple(map(lambda x: int(x) - 1, input().rstrip().split())) for _ in range(M)]
)
E = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))

dy = [-1, 1, 0, 0] # 상 하 좌 우 순서
dx = [0, 0, -1, 1]

answer = 0


def move(py: int, px: int) -> int:
"""
특정 참가자를 출구와 가까운 쪽으로 1만큼 이동시킨다.
이동 시 출구와 가까워지는 쪽으로, 상-하-좌-우 우선순위로 이동한다.

input : 이동시킬 참가자 (y, x) 좌표
output : 참가자 이동 여부 (이동했으면 1, 이동하지 않았으면 0)
"""
# 기존 참가자와 출구까지의 최단 거리
dist = abs(py - E[0]) + abs(px - E[1])

for d in range(4):
ny = py + dy[d]
nx = px + dx[d]
# 이동 후 참가자와 출구까지의 최단 거리
new_dist = abs(ny - E[0]) + abs(nx - E[1])
# 이동 가능하며, 출구와 가까워지는 경우
if 0 <= ny < N and 0 <= nx < N and matrix[ny][nx] == 0 and new_dist < dist:
# 이동 후 좌표가 탈출구인 경우 탈출시키고 아닌 경우, 이동시킨 좌표를 큐에 삽입
if (ny, nx) != E:
participants.append((ny, nx))
# 이동 성공 시 count 1 반환
return 1
# 이동 실패 시 원래 좌표를 다시 큐에 삽입, count 0 반환
participants.append((py, px))

return 0


def get_rectangle() -> Tuple[int, int, int, int]:
"""
출구와 최소 한 명의 참가자를 포함하는 최소 넓이 직사각형의 네 좌표를 반환한다.

input : x
output : 직사각형의 min_y, min_x, max_y, max_x
"""
rectangles = []

for y, x in set(participants):
max_y = max(y, E[0])
min_y = min(y, E[0])
max_x = max(x, E[1])
min_x = min(x, E[1])

# 한 변의 길이
side_len = max(max_y - min_y, max_x - min_x)
# 한 변의 길이를 유지하는 최소의 좌상단 좌표를 가지는 직사각형 좌표 구하기
min_y = max(max_y - side_len, 0)
max_y = min_y + side_len
min_x = max(max_x - side_len, 0)
max_x = min_x + side_len

rectangles.append((side_len**2, min_y, min_x, max_y, max_x))
# 우선순위 : 넓이 > 좌상단 y좌표 > 좌상단 x좌표
return min(rectangles)[1:]


def rotate(min_y: int, min_x: int, max_y: int, max_x: int) -> None:
"""
rotate시킬 정사각형의 좌표를 받아 시계방향으로 90도 회전시킨다.

input : rotate 시킬 정사각형의 min_y, min_x, max_y, max_x 좌표
output : x
"""
global E

participants_set = set(participants)
# rotate 시킬 부분의 임시 matrix
rotate_matrix = [
[0 for _ in range(min_x, max_x + 1)] for _ in range(min_y, max_y + 1)
]

# rotate전 정보 백업
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 벽의 경우 내구도 -1 시켜 백업
if matrix[y][x] > 0:
rotate_matrix[y - min_y][x - min_x] = matrix[y][x] - 1
# 출구 좌표 정보 백업
elif (y, x) == E:
rotate_matrix[y - min_y][x - min_x] = "E"
# 참가자 좌표 정보 백업
elif (y, x) in participants_set:
# 참가자는 동일 좌표에 여러명이 위치할 수 있음
cnt = 0
while (y, x) in participants:
cnt += 1
participants.remove((y, x))
# 참가자 한 명당 *의 개수로 백업
rotate_matrix[y - min_y][x - min_x] = "*" * cnt

# 해당 백업 matrix 90도 회전
rotate_matrix = [list(row)[::-1] for row in zip(*rotate_matrix)]

# 원본 matrix의 정사각형 위치를 90도 회전시킨 백업 matrix로 대치
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 회전 후 참가자 위치를 다시 큐에 삽입
if str(rotate_matrix[y - min_y][x - min_x]).startswith("*"):
# 기존 존재하던 참가자 수만큼 삽입
for _ in range(len(rotate_matrix[y - min_y][x - min_x])):
participants.append((y, x))
matrix[y][x] = 0
# 회전 후 출구 위치
elif rotate_matrix[y - min_y][x - min_x] == "E":
E = (y, x)
matrix[y][x] = 0
# 회전 후 벽의 내구도
else:
matrix[y][x] = rotate_matrix[y - min_y][x - min_x]


# 최대 k초 이동 가능
for i in range(K):
# 참가자 당 한 번씩 move
M = len(participants)
for _ in range(M):
answer += move(*participants.popleft())
# 이동 과정에서 참가자가 모두 탈출한 경우 종료
if not participants:
break
# 정사각형 좌표를 구해 해당 위치 90도 rotate
rotate(*get_rectangle())

print(answer)
print(E[0] + 1, E[1] + 1)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions CodeTree/메이즈 러너/jisu.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
"""
풀이 시작 : 2023-10-13 12:40 (이후 시간을 측정하지 않고 과제 느낌으로 풀이)
#### 제한사항
- 미로의 크기 : 4 <= N <= 10
- 참가자 수 : 1 <= M <= 10
- 게임 시간 : 1 <= K <= 100

#### 풀이
1. 이동
2. 회전
2-1. 정사각형 찾기
2-2. 회전시키기

풀이 완료 : 2023-10-14 18:03 (이틀동안 이거만 함 ㅎㅎ..)
수행시간 | 메모리
--|--
327ms | 27MB
"""

import sys
from typing import Tuple
from collections import deque

input = sys.stdin.readline

N, M, K = map(int, input().rstrip().split())

matrix = [list(map(int, input().rstrip().split())) for _ in range(N)]
participants = deque(
[tuple(map(lambda x: int(x) - 1, input().rstrip().split())) for _ in range(M)]
)
E = tuple(map(lambda x: int(x) - 1, input().rstrip().split()))

dy = [-1, 1, 0, 0] # 상 하 좌 우 순서
dx = [0, 0, -1, 1]

answer = 0


def move(py: int, px: int) -> int:
"""
특정 참가자를 출구와 가까운 쪽으로 1만큼 이동시킨다.
이동 시 출구와 가까워지는 쪽으로, 상-하-좌-우 우선순위로 이동한다.

input : 이동시킬 참가자 (y, x) 좌표
output : 참가자 이동 여부 (이동했으면 1, 이동하지 않았으면 0)
"""
# 기존 참가자와 출구까지의 최단 거리
dist = abs(py - E[0]) + abs(px - E[1])

for d in range(4):
ny = py + dy[d]
nx = px + dx[d]
# 이동 후 참가자와 출구까지의 최단 거리
new_dist = abs(ny - E[0]) + abs(nx - E[1])
# 이동 가능하며, 출구와 가까워지는 경우
if 0 <= ny < N and 0 <= nx < N and matrix[ny][nx] == 0 and new_dist < dist:
# 이동 후 좌표가 탈출구인 경우 탈출시키고 아닌 경우, 이동시킨 좌표를 큐에 삽입
if (ny, nx) != E:
participants.append((ny, nx))
# 이동 성공 시 count 1 반환
return 1
# 이동 실패 시 원래 좌표를 다시 큐에 삽입, count 0 반환
participants.append((py, px))

return 0


def get_rectangle() -> Tuple[int, int, int, int]:
"""
출구와 최소 한 명의 참가자를 포함하는 최소 넓이 직사각형의 네 좌표를 반환한다.

input : x
output : 직사각형의 min_y, min_x, max_y, max_x
"""
rectangles = []

for y, x in set(participants):
max_y = max(y, E[0])
min_y = min(y, E[0])
max_x = max(x, E[1])
min_x = min(x, E[1])

# 한 변의 길이
side_len = max(max_y - min_y, max_x - min_x)
# 한 변의 길이를 유지하는 최소의 좌상단 좌표를 가지는 직사각형 좌표 구하기
min_y = max(max_y - side_len, 0)
max_y = min_y + side_len
min_x = max(max_x - side_len, 0)
max_x = min_x + side_len

rectangles.append((side_len**2, min_y, min_x, max_y, max_x))
# 우선순위 : 넓이 > 좌상단 y좌표 > 좌상단 x좌표
return min(rectangles)[1:]


def rotate(min_y: int, min_x: int, max_y: int, max_x: int) -> None:
"""
rotate시킬 정사각형의 좌표를 받아 시계방향으로 90도 회전시킨다.

input : rotate 시킬 정사각형의 min_y, min_x, max_y, max_x 좌표
output : x
"""
global E

participants_set = set(participants)
# rotate 시킬 부분의 임시 matrix
rotate_matrix = [
[0 for _ in range(min_x, max_x + 1)] for _ in range(min_y, max_y + 1)
]

# rotate전 정보 백업
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 벽의 경우 내구도 -1 시켜 백업
if matrix[y][x] > 0:
rotate_matrix[y - min_y][x - min_x] = matrix[y][x] - 1
# 출구 좌표 정보 백업
elif (y, x) == E:
rotate_matrix[y - min_y][x - min_x] = "E"
# 참가자 좌표 정보 백업
elif (y, x) in participants_set:
# 참가자는 동일 좌표에 여러명이 위치할 수 있음
cnt = 0
while (y, x) in participants:
cnt += 1
participants.remove((y, x))
# 참가자 한 명당 *의 개수로 백업
rotate_matrix[y - min_y][x - min_x] = "*" * cnt

# 해당 백업 matrix 90도 회전
rotate_matrix = [list(row)[::-1] for row in zip(*rotate_matrix)]

# 원본 matrix의 정사각형 위치를 90도 회전시킨 백업 matrix로 대치
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# 회전 후 참가자 위치를 다시 큐에 삽입
if str(rotate_matrix[y - min_y][x - min_x]).startswith("*"):
# 기존 존재하던 참가자 수만큼 삽입
for _ in range(len(rotate_matrix[y - min_y][x - min_x])):
participants.append((y, x))
matrix[y][x] = 0
# 회전 후 출구 위치
elif rotate_matrix[y - min_y][x - min_x] == "E":
E = (y, x)
matrix[y][x] = 0
# 회전 후 벽의 내구도
else:
matrix[y][x] = rotate_matrix[y - min_y][x - min_x]


# 최대 k초 이동 가능
for i in range(K):
# 참가자 당 한 번씩 move
M = len(participants)
for _ in range(M):
answer += move(*participants.popleft())
# 이동 과정에서 참가자가 모두 탈출한 경우 종료
if not participants:
break
# 정사각형 좌표를 구해 해당 위치 90도 rotate
rotate(*get_rectangle())

print(answer)
print(E[0] + 1, E[1] + 1)