빠르고 귀여운 코드
문제
https://www.acmicpc.net/problem/1012
나의 풀이
다른 답안에 비해 시간이 좀 더 빠르게 나오는데 sys의 readline을 썼기 때문이라 생각한다.
이전에 작성한 코드보다 좀 더 간결하게 정리된 코드인 것 같아 맘에 든다.
count_worm의 direction과 q를 이용해 작성된 BFS가 특징이다.
import sys
read = lambda: sys.stdin.readline().strip()
def mapping_land(m: int, n: int, k: int) -> list:
land_map = [[0 for _ in range(n)] for _ in range(m)]
for _ in range(k):
i, j = map(int, read().split())
land_map[i][j] = 1
return land_map
def count_worm(m: int, n: int, land_map: list) -> int:
direction = [(1, 0), (0, -1), (-1, 0), (0, 1)]
count = 0
for i in range(m):
for j in range(n):
if land_map[i][j] != 0:
count += 1
q = [(i, j)]
while q:
coord = q.pop()
x = coord[0]
y = coord[1]
land_map[x][y] = 0
for go_x, go_y in direction:
if (
0 <= go_x + x < m
and 0 <= go_y + y < n
and land_map[go_x + x][go_y + y] == 1
):
q.append((go_x + x, go_y + y))
return count
if __name__ == "__main__":
t = int(read())
for _ in range(t):
m, n, k = map(int, read().split())
land_map = mapping_land(m, n, k)
print(count_worm(m, n, land_map))
댓글남기기