728x90
반응형
기본적인 DFS & BFS 문제이다.
DFS 풀이
import sys
sys.setrecursionlimit(3000000)
def dfs(y, x):
graph[y][x] = '*'
for dy, dx in d:
Y, X = y+dy, x+dx
if (0 <= Y < m) and (0 <= X < n) and graph[Y][X] == '@':
dfs(Y, X)
while 1:
m, n = map(int, input().split())
if m == n == 0:
break
graph = [list(input()) for _ in range(m)]
d = [(-1, -1), (-1, 1), (1, -1), (1, 1), (-1, 0), (1, 0), (0, -1), (0, 1)]
cnt = 0
for i in range(m):
for j in range(n):
if graph[i][j] == '@':
dfs(i, j)
cnt += 1
print(cnt)
BFS 풀이
from collections import deque
def bfs(y, x):
q = deque()
q.append((y, x))
graph[y][x] = '*'
while q:
y, x = q.popleft()
for dy, dx in d:
Y, X = y+dy, x+dx
if (0 <= Y < m) and (0 <= X < n) and graph[Y][X] == '@':
q.append((Y, X))
graph[Y][X] = '*'
while 1:
m, n = map(int, input().split())
if m == n == 0:
break
graph = [list(input()) for _ in range(m)]
d = [(-1, -1), (-1, 1), (1, -1), (1, 1), (-1, 0), (1, 0), (0, -1), (0, 1)]
cnt = 0
for i in range(m):
for j in range(n):
if graph[i][j] == '@':
bfs(i, j)
cnt += 1
print(cnt)
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 18243번 Small World Network(python) (0) | 2021.03.14 |
---|---|
백준 알고리즘 18232번 텔레포트 정거장(python) (0) | 2021.03.14 |
백준 알고리즘 17198번 Bucket Brigade(python) (0) | 2021.03.14 |
백준 알고리즘 11123번 양 한마리... 양 두마리...(python) (0) | 2021.03.14 |
백준 알고리즘 6186번 Best Grass(python) (0) | 2021.03.12 |