2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
from collections import deque
N = int(input())
graph = []
for i in range(N):
graph.append(list(map(int, input())))
dx, dy = [1,-1,0,0], [0,0,1,-1]
def bfs(g, r, c):
q = deque([(r, c)])
g[r][c] = 0
cnt = 1
while q:
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx<0 or N<=nx or ny<0 or N<=ny:
continue
if g[nx][ny] == 1:
cnt += 1
g[nx][ny] = 0
q.append((nx, ny))
return cnt
cnt_lst = []
for i in range(N):
for j in range(N):
if graph[i][j] == 1:
cnt_lst.append(bfs(graph, i, j))
cnt_lst.sort()
print(len(cnt_lst))
for c in cnt_lst:
print(c)
11724번: 연결 요소의 개수
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주
www.acmicpc.net
from collections import deque
N, M = map(int, input().split())
graph = [[] for _ in range(N+1)]
visited = [False]*(N+1)
cnt = 0
for _ in range(M):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
def bfs(start):
q = deque([start])
visited[start] = True
while q:
node = q.popleft()
for adj_node in graph[node]:
if not visited[adj_node]:
visited[adj_node] = True
q.append(adj_node)
for node in range(1, N+1):
if visited[node]:
continue
visited[node] = True
cnt += 1
for adj_node in graph[node]:
bfs(adj_node)
print(cnt)
14502번: 연구소
인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다. 연구소는 크
www.acmicpc.net
from collections import deque
import copy
from itertools import combinations
# 입력받기
N, M = map(int, input().split())
graph = []
for _ in range(N):
graph.append(list(map(int, input().split())))
# 바이러스 위치
blank_position = []
for i in range(N):
for j in range(M):
if graph[i][j] == 0:
blank_position.append((i, j))
# 벽을 설치할 후보지 조합
wall_candidates = combinations(blank_position, 3)
# bfs
dx, dy = [0,0,1,-1], [1,-1,0,0]
def bfs(g):
q = deque()
# 초기 바이러스 장소 큐에 넣기
for i in range(N):
for j in range(M):
if g[i][j] == 2:
q.append((i, j))
# 바이러스 퍼트리기
while q:
x, y = q.popleft()
for i in range(4):
nx = x+dx[i]
ny = y+dy[i]
if nx<0 or N<=nx or ny<0 or M<=ny:
continue
if g[nx][ny] == 0:
g[nx][ny] = 2
q.append((nx, ny))
max_safe_area = 0
for walls in wall_candidates:
safe_area = 0
g = copy.deepcopy(graph)
# 벽설치
for p in walls:
g[p[0]][p[1]] = 1
# 바이러스 퍼짐
bfs(g)
# 안전지역 넓이 계산
for i in range(N):
for j in range(M):
if g[i][j] == 0:
safe_area += 1
max_safe_area = max(max_safe_area, safe_area)
print(max_safe_area)
'Python' 카테고리의 다른 글
[Python] 한글문서 편집 자동화하기 #2 (0) | 2023.04.02 |
---|---|
[Python] 한글문서 편집 자동화하기 #1 (0) | 2023.03.15 |
[Python] 코딩테스트 연습 (0) | 2023.02.10 |
[Python] Youtube Downloader #2 (0) | 2023.01.28 |
[Python] Youtube Downloader #1 (0) | 2022.11.23 |