[BOJ]1012(python)

zzarbttoo·2021년 10월 12일
0

성장형으로 플레를 가기 위해 노력하는 중
오늘은 1트에 해결을 해보았다 이히

import collections

def solution():

    M, N, K = map(int, input().split())
    field = collections.defaultdict(lambda: collections.defaultdict(lambda :-1))
    direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    K_list = []
    count = 0

    for _ in range(K):
        X, Y = map(int, input().split())
        field[X][Y] = 1
        K_list.append([X, Y])

    def search(now_x, now_y):

        field[now_x][now_y] = -1

        for direct in direction:
            next_x, next_y = now_x + direct[0], now_y + direct[1]
            if next_x >= 0 and next_x < M and next_y >= 0 and next_y < N:
                if field[next_x][next_y] == 1:
                    search(next_x, next_y)

    count = 0

    for k in K_list:
        if field[k[0]][k[1]] == 1:
            count += 1
            search(k[0], k[1])

    return count

test_case = int(input())

for _ in range(test_case):
    print(solution())
  • defaultdict(lambda : defaultdict(lambda : -1))로 해서 맨 처음에는 방문을 하지 않은 것으로 초기화했다
  • 배추에 방문을 했으면 1로 바꾸도록 했으며, 붙어있는 배추들 모두 방문한 것으로 했다(재귀 이용)
  • 새로운 배추 구역에 방문할 때 count + 1을 해서 배추 구역 갯수를 구했다

네이버 클라우드 코테에 나온 문제랑 약간 비슷했는데
이게 silver2문제인게 무서웠다(나 너무 무서워우어~)

플레로 가는 길은 험난할 것 같다 🎢

profile
나는야 누워있는 개발머신

0개의 댓글