1012번: 유기농 배추
python
import sys
sys.setrecursionlimit(20000)
T = int(input())
for t in range(T):
M, N, K = [int(x) for x in input().split()]
map_ = [[0 for j in range(N)] for i in range(M)]
def erase(i, j):
if map_[i][j]:
map_[i][j] = 0
if i > 0:
erase(i - 1, j)
if j > 0:
erase(i, j - 1)
if i < M - 1:
erase(i + 1, j)
if j < N - 1:
erase(i, j + 1)
cnt = 0
for k in range(K):
i, j = [int(x) for x in input().split()]
map_[i][j] = 1
for i in range(M):
for j in range(N):
if map_[i][j]:
cnt += 1
erase(i, j)
print(cnt)
첫 번째 풀이는 런타임에러(RecursionError) 때문에 고생했다..
T = int(input())
for _ in range(T):
_, _, K = [int(x) for x in input().split()]
cabs = [[int(x) for x in input().split()] for _ in range(K)]
temp = []
cnt = 0
while cabs:
temp.append(cabs.pop())
cnt += 1
while temp:
i, j = temp.pop()
neighbors = [[i - 1, j], [i, j - 1], [i + 1, j], [i, j + 1]]
for n in neighbors:
if n in cabs:
cabs.remove(n)
temp.append(n)
print(cnt)