https://www.acmicpc.net/problem/1012
BFS 사용
인접행렬 adjMatrix
(bfs 함수)
(입력 및 선언)
(배추 위치 찾기)
(최종 출력)
DFS 사용
Recursion 에러가 나서 재귀 깊이를 설정해주어야 한다.
인접행렬 adjMatrix
(dfs 함수)
(입력 및 선언)
(배추 위치 찾기)
(최종 출력)
BFS
from collections import deque
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
# bfs - queue
def bfs() :
while bfsQueue :
currentLocation = bfsQueue.popleft()
curY = currentLocation[0]
curX = currentLocation[1]
for i in range(4) :
ny = curY + dy[i]
nx = curX + dx[i]
if ny < 0 or nx < 0 or ny >= n or nx >= m :
continue
if adjMatrix[ny][nx] == 0 :
continue
if visited[ny][nx] != 0 :
continue
visited[ny][nx] = True
bfsQueue.append((ny, nx))
t = int(input())
for _ in range(t) :
m, n, k = list(map(int, input().split()))
adjMatrix = [[0 for _ in range(m)] for _ in range(n)]
visited = [[False for _ in range(m)] for _ in range(n)]
bfsQueue = deque([])
cnt = 0
for _ in range(k) :
x, y = list(map(int, input().split()))
adjMatrix[y][x] = 1
# bfs - visited, queue, bfs 호출
for i in range(n) :
for j in range(m) :
if adjMatrix[i][j] == 1 and visited[i][j] == 0 :
bfsQueue.append((i, j))
visited[i][j] = True
bfs()
cnt += 1
print(cnt)
DFS
import sys
sys.setrecursionlimit(10000) # 재귀 깊이 설정
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
# dfs - Recursion
def dfs(y, x) :
global cnt
for i in range(4) :
ny = y + dy[i]
nx = x + dx[i]
if ny < 0 or nx < 0 or ny >= n or nx >= m :
continue
if adjMatrix[ny][nx] == 0 :
continue
if visited[ny][nx] != 0 :
continue
visited[ny][nx] = 1
dfs(ny, nx)
t = int(input())
for _ in range(t) :
m, n, k = list(map(int, input().split()))
adjMatrix = [[0 for _ in range(m)] for _ in range(n)]
visited = [[False for _ in range(m)] for _ in range(n)]
cnt = 0
for _ in range(k) :
x, y = list(map(int, input().split()))
adjMatrix[y][x] = 1
# dfs - visited, dfs
for i in range(n) :
for j in range(m) :
if adjMatrix[i][j] == 1 and visited[i][j] == 0 :
visited[i][j] = True
dfs(i, j)
cnt += 1
print(cnt)
y축이 n
x축이 m
세로가 n, 가로가 m
둘이 너무 헷갈린다 ...