시간초과
from collections import deque
N,M = map(int, input().split())
grid = []
for i in range(N):
row = list(map(int, input().split()))
grid.append(row)
dx = [0,1,0,-1]
dy = [1,0,-1,0]
max_result = 0
def virusBlow():
test_grid = [row[:] for row in grid]
queue = deque()
for y in range(N):
for x in range(M):
if test_grid[y][x] == 2:
queue.append((x, y))
while queue:
cx, cy = queue.popleft()
for i in range(4):
nx, ny = cx + dx[i], cy + dy[i]
if 0 <= nx < M and 0 <= ny < N:
if test_grid[ny][nx] == 0:
test_grid[ny][nx] = 2
queue.append((nx, ny))
cnt = 0
for row in test_grid:
cnt += row.count(0)
return cnt
def makeWall(count):
global max_result
if count == 3:
max_result = max(max_result, virusBlow())
return
for y in range(N):
for x in range(M):
if grid[y][x] == 0:
grid[y][x] = 1
makeWall(count + 1)
grid[y][x] = 0
makeWall(0)
print(max_result)
해결코드
from itertools import combinations
from collections import deque
empty_spaces = []
for y in range(N):
for x in range(M):
if grid[y][x] == 0:
empty_spaces.append((x, y))
for walls in combinations(empty_spaces, 3):
for wx, wy in walls:
grid[wy][wx] = 1
max_result = max(max_result, virusBlow())
for wx, wy in walls:
grid[wy][wx] = 0
- 불필요한 루프 제거
- 벽을 세울 수 없는 곳(1이나 2가 있는 곳)을 매번 검사하지 않고, 오직
empty_spaces만 대상
- 함수 호출 오버헤드 감소
- 재귀 함수(
makeWall)를 수만 번 호출하는 비용을 줄일 수 있음