728x90
반응형
DFS & BFS 문제이다.
BFS 풀이
from collections import deque
def bfs(i, j):
queue = deque()
queue.append((i, j))
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
cnt = 1
while queue:
y, x = queue.popleft()
for dy, dx in d:
Y, X = y+dy, x+dx
if (0 <= Y < N) and (0 <= X < M) and graph[Y][X] == 1:
queue.append((Y, X))
graph[Y][X] = 0
cnt += 1
return cnt
N, M, K = map(int, input().split())
graph = [[0]*M for _ in range(N)]
for _ in range(K):
y, x = map(int, input().split())
graph[y-1][x-1] = 1
res = []
for i in range(N):
for j in range(M):
if graph[i][j] == 1:
graph[i][j] = 0
res.append(bfs(i, j))
print(max(res))
DFS 풀이
import sys
sys.setrecursionlimit(10000)
def dfs(y, x, cnt):
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
graph[y][x] = 0
for dy, dx in d:
Y, X = y+dy, x+dx
if (0 <= Y < N) and (0 <= X < M) and graph[Y][X] == 1:
cnt = dfs(Y, X, cnt+1)
return cnt
N, M, K = map(int, input().split())
graph = [[0]*M for _ in range(N)]
for _ in range(K):
y, x = map(int, input().split())
graph[y-1][x-1] = 1
res = []
for i in range(N):
for j in range(M):
if graph[i][j] == 1:
res.append(dfs(i, j, 1))
print(max(res))
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 2583번 영역 구하기(python) (0) | 2021.03.10 |
---|---|
백준 알고리즘 2468번 안전 영역(python) (0) | 2021.03.10 |
백준 알고리즘 1926번 그림(python) (0) | 2021.03.10 |
백준 알고리즘 18870번 좌표 압축(python) (0) | 2021.03.10 |
백준 알고리즘 1697번 숨바꼭질(python) (0) | 2021.03.10 |