🔬 연구소

  • 시간제한: 2초
  • 메모리 제한: 512MB

📄 문제

  • 인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다.
  • 연구소는 크기가 N x M인 직사각형으로 나타낼 수 있으며, 직사각형은 1 x 1 크기의 정사각형으로 나누어져 있다. 연구소는 빈 칸, 벽으로 이루어져 있으며, 벽은 칸 하나를 가득 차지한다.
  • 일부 칸은 바이러스가 존재하며, 이 바이러스는 상하좌우로 인접한 빈 칸으로 모두 퍼져나갈 수 있다.
  • 새로 세울 수 있는 벽의 개수는 3개이며, 꼭 3개를 세워야 한다.
  • 예를 들어, 아래와 같이 연구소가 생긴 경우를 살펴보자.

  • 이때, 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 곳이다. 아무런 벽을 세우지 않았다면, 바이러스는 모든 빈 칸으로 퍼져나갈 수 있다.
  • 2행 1열, 1행 2열, 4행 6열에 벽을 세운다면 지도의 모양은 아래와 같아지게 된다.

  • 바이러스가 퍼진 뒤의 모습은 아래와 같아진다.

  • 벽을 3개 세운 뒤, 바이러스가 퍼질 수 없는 곳을 안전 영역이라고 한다.
  • 위의 지도에서 안전 영역의 크기는 27이다.
  • 연구소의 지도가 주어졌을 때 얻을 수 있는 안전 영역 크기의 최댓값을 구하는 프로그램을 작성하시오.

입력

  • 첫째 줄에 지도의 세로 크기 N과 가로 크기 M이 주어진다.( 3 <= N, M <= 8)
  • 둘째 줄 부터 N개의 줄에 지도의 모양이 주어진다. 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 위치이다.
  • 2의 개수는 2보다 크거나 같고, 10보다 작거나 같은 자연수이다.
  • 빈 칸의 개수는 3개 이상이다.

출력

  • 첫째 줄에 얻을 수 있는 안전 영역의 최대 크기를 출력한다.

 

💡 문제 아이디어

  • bfs/dfs문제 인 것 같은데 이를 활용하여 어떤 방식으로 구현해야 할지 감이 오지 않아서 다른 사람 풀이에서 주석을 통해 로직만 참고
    1. 하나씩 펜스를 친다.
      • 펜스가 3개가 되면 바이러스 전파해서 안전영역 센다.
      • 3개 미만이면 펜스 계속 치기

✅ 정답 코드 (풀이 참고 + GPT 활용)

# 연구소
from sys import stdin
from collections import deque
import copy

input = stdin.readline

# 세로, 가로 입력
N, M = map(int, input().split())

# 연구소 지도 입력
lab = [list(map(int, input().split())) for _ in range(N)]

# 바이러스 위치 저장
viruses = []

# 빈곳 위치 저장
empty_spaces = []

for i in range(N):
    for j in range(M):
        if lab[i][j] == 2:
            viruses.append((i, j))
        elif lab[i][j] == 0:
            empty_spaces.append((i, j))

# 안전영역 최대값 저장
max_safe = -1

def virus_and_return_safe():
    global result
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    temp_lab = copy.deepcopy(lab)
    queue = deque(viruses)

    while queue:
        x, y = queue.popleft()

        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            if 0 <= nx < N and 0 <= ny < M and temp_lab[nx][ny] == 0:
                temp_lab[nx][ny] = 2
                queue.append((nx, ny))
    cnt = 0
    for i in range(N):
        cnt += temp_lab[i].count(0)

    result = max(result, cnt)



def make_wall(cnt, index):
    if cnt == 3:
        virus_and_return_safe()
        return
    for i in range(index, len(empty_spaces)):
        x, y = empty_spaces[i]
        lab[x][y] = 1
        make_wall(cnt + 1, i + 1)
        lab[x][y] = 0 # 백트래킹
result = 0
make_wall(0, 0)
print(result)
728x90

🧱 벽부수고 이동하기

  • 시간제한: 2초
  • 메모리 제한: 192MB

📄 문제

  • N x M의 행렬로 표현되는 맵이 있다. 
  • 맵에서는 0은 이동할 수 있는 곳을 나타내고, 1은 이동할 수 없는 벽이 있는 곳을 나타낸다.
  • 당신은 (1,1) 에서 (N, M)의 위치까지 이동하려 하는데, 이때 최단 경로로 이동하려 한다.
  • 최단경로는 맵에서 가장 적은 개수의 칸을 지나는 경로를 말하는데, 이때 시작하는 칸과 끝나는 칸도 포함해서 센다.
  • 만약에 이동하는 도중에 한 개의 벽을 부수고 이동하는 것이 좀 더 경로가 짧아진다면, 벽을 한 개 까지 부수고 이동하여도 된다.
  • 한 칸에서 이동할 수 있는 칸은 상하좌우로 인접한 칸이다.
  • 맵이 주어졌을 때, 최단 경로를 구해내는 프로그램을 작성하시오.

입력

  • 첫 줄에 N(1 <= N <= 1000), M(1 <= M <= 1000)이 주어진다.
  • 다음 N개의 줄에  M개의 숫자로 맵이 주어진다.
  • (1,1)과 (N, M)은 항상 0이라고 가정하자.

출력

  • 첫째 줄에 최단 거리를 출력한다. 불가능할 때는 -1을 출력한다.

💡 문제 접근 아이디어

  • (1, 1)과 (N, M) 각각 하, 우와 상, 좌가 1인 경우 == -1
  • 가다가 길이 끊기는 경우 == -1
  • DFS 알고리즘

 

❌ 2% 틀렸습니다.

  • 너무 단순하게 예제 코드에만 맞춰서 생각한 것 같다.
  • 다시 생각해보자.
  • DFS가 아니라 BFS로 풀어야 하는게 맞는 것 같음! 
from sys import stdin

input = stdin.readline

N, M = map(int, input().split())
walls = []

for _ in range(N):
    walls.append(list(map(int, input().strip())))

# (1,1)과 (N,M)이 1로 가로막혀 있는지 확인
start = walls[0][1] and walls[1][0]
end = walls[N-1][M-2] and walls[N-2][M-1]

if start and end:
    print(-1)
    exit()


def dfs(graph, start):
    # start (x, y, value, walls-flag)
    stack = [start]

    # directions
    directionsX = [1, -1, 0, 0]
    directionsY = [0, 0, -1, 1]

    while stack:
        x, y, value, flag = stack.pop()
        # print(x, y, value, flag)
        # for g in graph:
        #     print(g)
        # print()

        graph[x][y] = min(value, graph[x][y]) if graph[x][y] > 1 else value

        for i in range(len(directionsX)):
            nx, ny = x + directionsX[i], y + directionsY[i]
            if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] in [0, 1]:
                if flag:
                    if graph[nx][ny] == 0:
                        stack.append((nx, ny, value + 1, flag))
                else:
                    if graph[nx][ny] == 1:
                        stack.append((nx, ny, value + 1, True))
                    else:
                        stack.append((nx, ny, value + 1, flag))
    return graph

result = dfs(walls, (0, 0, 2, False))

if result[N-1][M-1] > 1:
    print(result[N-1][M-1] - 1)
else:
    print(-1)

 

❌ 메모리 초과 >> 이런,,

  • visited check할때 set 사용, 4 tuple 사용 등 이슈로 메모리 초과가 난 것 같다는 예상 >> 3차원 배열로 visited 선언해서 방문 체크로 변경
from sys import stdin
from collections import deque

input = stdin.readline

N, M = map(int, input().split())
walls = []

for _ in range(N):
    walls.append(list(map(int, input().strip())))

# (1,1)과 (N,M)이 1로 가로막혀 있는지 확인
start = walls[0][1] and walls[1][0]
end = walls[N-1][M-2] and walls[N-2][M-1]

if start and end:
    print(-1)
    exit()


def bfs(graph, start):
    # start (x, y, value, walls-flag)
    queue = deque([start])

    # directions
    directionsX = [-1, 1, 0, 0]
    directionsY = [0, 0, 1, -1]

    while queue:
        x, y, value, flag = queue.popleft()
        # print(x, y, value, flag)
        # for g in graph:
        #     print(g)
        # print(graph[x][y], value)
        # print()

        graph[x][y] = min(value, graph[x][y]) if graph[x][y] > 1 else value

        for i in range(len(directionsX)):
            nx, ny = x + directionsX[i], y + directionsY[i]
            if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] in [0, 1]:
                if flag:
                    if graph[nx][ny] == 0:
                        queue.append((nx, ny, value + 1, flag))
                else:
                    if graph[nx][ny] == 1:
                        queue.append((nx, ny, value + 1, True))
                    else:
                        queue.append((nx, ny, value + 1, flag))
    return graph

result = bfs(walls, (0, 0, 2, False))

if result[N-1][M-1] > 1:
    print(result[N-1][M-1] - 1)
else:
    print(-1)


# 7 4
# 0000
# 1110
# 1000
# 1000
# 0000
# 0111
# 0000
# answer: 10

 

✅  성공 코드 

from sys import stdin
from collections import deque

input = stdin.readline

N, M = map(int, input().split())
walls = []

for _ in range(N):
    walls.append(list(map(int, input().strip())))

def bfs(graph, start):
    queue = deque([start])
    visited = [[[0, 0] for _ in range(M)] for _ in range(N)]
    visited[0][0][0] = 1 # 시작점 방문 표시

    # directions
    directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]

    while queue:
        x, y, flag = queue.popleft()

        if x == N - 1 and y == M - 1:
            return visited[x][y][flag]

        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            if 0 <= nx < N and 0 <= ny < M:
                # 벽이 아니고 아직 방문하지 않은 경우
                if graph[nx][ny] == 0 and visited[nx][ny][flag] == 0:
                    visited[nx][ny][flag] = visited[x][y][flag] + 1
                    queue.append((nx, ny, flag))
                # 벽이고 아직 벽을 부수지 않은 경우
                elif graph[nx][ny] == 1 and flag == 0 and visited[nx][ny][1] == 0:
                    visited[nx][ny][1] = visited[x][y][0] + 1
                    queue.append((nx, ny, 1))
    # 도달할 수 없을 경우
    return -1

print(bfs(walls, (0, 0, 0)))


# 7 4
# 0000
# 1110
# 1000
# 1000
# 0000
# 0111
# 0000
# answer: 10
728x90

🍅 토마토

  • 시간 제한: 1초
  • 메모리 제한: 256MB

📄 문제 

  • 철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 아래의 그림과 같이 격자 모양 상자의 칸에 하나씩 넣어서 창고에 보관한다.

  • 창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 
  • 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다.
  • 하나의 토마토의 인접한 곳은 왼쪽, 오른쪽, 앞, 뒤 네 방향에 있는 토마토를 의미한다. 
  • 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다.
  • 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지, 그 최소 일수를 알고 싶어 한다.
  • 토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라.
  • 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.

입력

  • 첫 줄에는 상자의 크기를 나타내는 두 정수 M, N이 주어진다.
  • M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다.
  • 단, 2 <= M, N <= 1000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다.
  • 토마토가 하나 이상 있는 경우만 주어진다.

출력

  • 여러분은 토마토가 모두 익을 때까지의 최소 날짜를 출력해야 한다.
  • 만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.

💡 문제 풀이 아이디어

  • 알고리즘: BFS
  • end 조건:
    1. 토마토가 모두 익은 상태: set(Tomato) == {1, -1} 인 경우
    2. 토마토가 모두 익지 못하는 상황: 0인 토마토 주위에 -1만 있는 경우

 

❌ 85% 틀렸습니다 코드 

  • 어떤 예외처리를 못했을지 고민,,
  • 마지막에 bfs돌린 후 모든 토마토가 익었는지 안익었는지 확인하는 코드를 빼먹음
from sys import stdin
from collections import deque
input = stdin.readline


M, N = map(int, input().split())
# M 가로, N 세로
tomatoes = []
set_tomatoes = set()
day = 0

for _ in range(N):
    inputs = list(map(int, input().split()))
    set_tomatoes.update(set(inputs))
    tomatoes.append(inputs)

# 현재 모든 토마토가 있었는지 확인하기
if len(set_tomatoes) == 1 and set_tomatoes.pop() == 1:
    print(0)
    exit()

# 익은 토마토가 없는 경우
if 1 not in set_tomatoes:
    print(-1)
    exit()

queue = deque([])

# 익은 토마토들 queue에 담기
for x in range(N):
    for y in range(M):
        if tomatoes[x][y] == 1:
            queue.append((x, y))

# bfs
def bfs(graph, queue):
    # 상 하 좌 우
    directionX = [-1, 1, 0, 0]
    directionY = [0, 0, -1, 1]

    next = deque([])

    while queue:
        x, y = queue.popleft()
        for i in range(len(directionX)):
            nx, ny = x + directionX[i], y + directionY[i]
            if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] == 0:
                graph[nx][ny] = 1
                next.append((nx, ny))
    return graph, next

while queue:
    tomatoes, queue = bfs(tomatoes, queue)
    day += 1
    # print(day, queue)
    # 
    # for tomato in tomatoes:
    #     print(tomato)

print(day - 1)

 

✅ 정답 코드

from sys import stdin
from collections import deque
input = stdin.readline


M, N = map(int, input().split())
# M 가로, N 세로
tomatoes = []
set_tomatoes = set()
day = 0

for _ in range(N):
    inputs = list(map(int, input().split()))
    set_tomatoes.update(set(inputs))
    tomatoes.append(inputs)

# 현재 모든 토마토가 있었는지 확인하기
if len(set_tomatoes) == 1 and set_tomatoes.pop() == 1:
    print(0)
    exit()

# 익은 토마토가 없는 경우
if 1 not in set_tomatoes:
    print(-1)
    exit()

queue = deque([])

# 익은 토마토들 queue에 담기
for x in range(N):
    for y in range(M):
        if tomatoes[x][y] == 1:
            queue.append((x, y))

# bfs
def bfs(graph, queue):
    # 상 하 좌 우
    directionX = [-1, 1, 0, 0]
    directionY = [0, 0, -1, 1]

    next = deque([])

    while queue:
        x, y = queue.popleft()
        for i in range(len(directionX)):
            nx, ny = x + directionX[i], y + directionY[i]
            if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] == 0:
                graph[nx][ny] = 1
                next.append((nx, ny))
    return graph, next

while queue:
    tomatoes, queue = bfs(tomatoes, queue)
    day += 1

for tomato in tomatoes:
    # 익지 않은 토마토가 있는지 확인
    if 0 in tomato:
        print(-1)
        exit()
print(day - 1)
728x90

IF문 좀 대신 써줘

시간초과 코드

from sys import stdin

N, M = map(int, stdin.readline().strip().split())

powers = []
titles = []

for _ in range(N):
    title, power = map(str, stdin.readline().strip().split())
    power = int(power)
    powers.append(power)
    titles.append(title)

for _ in range(M):
    userPower = int(stdin.readline().strip())
    for idx in range(len(powers)):
        if userPower <= powers[idx]:
            print(titles[idx])
            break

 

성공 코드

from sys import stdin

N, M = map(int, stdin.readline().strip().split())

powers = []

for _ in range(N):
    title, power = map(str, stdin.readline().strip().split())
    powers.append([title, int(power)])


powers.sort(key=lambda x: x[1]) # 오름차순 정렬

for _ in range(M):
    power = int(stdin.readline().strip())
    start = 0
    end = len(powers)-1

    while start <= end:
        mid = (start+end) // 2
        if power > powers[mid][1]:
            start = mid + 1
        else:
            end = mid - 1

    print(powers[start][0])
728x90

+ Recent posts