티스토리 뷰
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
from itertools import combinations # 조합을 위해 사용
from collections import deque
from copy import deepcopy # 이차원 배열 복사를 위해 사용
n, m = list(map(int, input().split()))
graph = []
for i in range(n):
graph.append(list(map(int, input().split())))
safe = []
for i in range(n):
for j in range(m):
if graph[i][j] == 0:
safe.append((i, j))
# 상하좌우 이동
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(graph, x, y):
visited = [[False for _ in range(m)] for _ in range(n)]
q = deque()
q.append((x, y))
while q:
x, y = q.popleft()
visited[x][y] = True
for i in range(4): # 상하좌우 검색
new_x = x + dx[i]
new_y = y + dy[i]
if new_x < 0 or new_x >= n or new_y < 0 or new_y >= m: # 배열의 크기를 벗어나는 경우 제외
continue
if graph[new_x][new_y] != 0:
continue
if not visited[new_x][new_y]:
graph[new_x][new_y] = 2
q.append((new_x, new_y))
return graph
combs = list(combinations(safe, 3)) # 벽을 3개 세우는 경우 찾기
max_count = 0
for comb in combs:
new_graph = deepcopy(graph) # 이차원 배열 복사
for x, y in comb:
new_graph[x][y] = 1
for x in range(n):
for y in range(m):
if new_graph[x][y] == 2:
new_graph = bfs(new_graph, x, y)
# 안전 지대 0 체크
count = 0
for x in range(n):
for y in range(m):
if new_graph[x][y] == 0:
count += 1
# 가장 안전지대의 수가 많은 것을 선택
max_count = max(max_count, count)
print(max_count)
|
cs |
파이썬으로 돌리면 시간초과가 나온다. pypy3로 돌리면 정답임을 확인할 수 있다.
이차원 배열의 deepcopy에서 시간을 많이 사용하는 것 같다. deepcopy 없이 문제를 푸는 방법을 고민 해봐야겠다.
'알고리즘 문제 > 백준 - 파이썬' 카테고리의 다른 글
백준 2206번: 벽 부수고 이동하기 [python/파이썬] (0) | 2020.10.10 |
---|---|
백준 16236번: 아기 상어 [python/파이썬] (0) | 2020.10.03 |
백준 1260번 - DFS와 BFS [python/파이썬] (0) | 2020.09.10 |
백준 2981 - 검문 [python/파이썬] (0) | 2020.09.07 |
백준 1920번 - 수 찾기 [python/파이썬] (0) | 2020.09.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- localhost https
- 리액트 동작원리
- 리액트 props
- 해쉬 라우터
- 백준
- props를 변경하지 못하는 이유
- Browser Router
- 프론트
- 리액트 리스트 키
- 프론트엔드
- React key
- 브라우저 라우터
- props를 변경하지 않는 이유
- 우테코
- mkcert
- 파이썬
- 리액트 jsx
- 리액트 키
- 리액트 리스트 key
- Hash Router
- 1463
- Redux Thunk
- Python
- 리액트 리덕스
- 다라쓰
- 리덕스 썽크
- 우아한테크코스
- 인사이트
- 댓글 모듈
- contentEditable focus
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함