백준 1012번 파이썬 풀이

홍태리·2022년 3월 5일
0

백준

목록 보기
8/9
post-thumbnail

첫 시도, 잘못된 코드

#백준 1012번

#인접해있는 배추 그룹 찾기 함수 정의
def find_cabbage_group(row:int, col:int, index:int, cabbage_coordinates:list, visited:list) -> int:
    #이미 방문한 배추일 경우 무시
    if visited[index]:
        return 0

    #cabbage_coordinates를 돌며 주어진 (row, col)과 인접한 좌표가 리스트 안에 존재하는지 확인
    for index, coordinate in enumerate(cabbage_coordinates):
        #(row, col)의 인접 좌표가 배추 좌표와 동일한 경우
        if [row-1, col] == coordinate:
            #해당 배추 좌표를 방문처리 및 재귀함수 호출
            visited[index] = True
            find_cabbage_group(row-1, col, index, cabbage_coordinates, visited)
        elif [row, col-1] == coordinate:
            visited[index] = True
            find_cabbage_group(row, col-1, index, cabbage_coordinates, visited)
        elif [row, col+1] == coordinate:
            visited[index] = True
            find_cabbage_group(row, col+1, index, cabbage_coordinates, visited)
        elif [row+1, col] == coordinate:
            visited[index] = True
            find_cabbage_group(row+1, col, index, cabbage_coordinates, visited)
        else:
            continue
    return 1

#테스트 케이스 개수 받기
testcase_num = int(input())
answer_list = []

#각 테스트 케이스에 대하여 배추밭의 가로 길이, 세로 길이, 배추 개수 받기
for _ in range(testcase_num):
    colomn_num, row_num, cabbage_num = map(int, input().split())

    #배추 위치 좌표 받기
    cabbage_coordinates = []
    for _ in range(cabbage_num):
        cabbage_coordinates.append(list(map(int, input().split())))

    #각 배추 위치 좌표의 방문 여부 리스트 정의
    visited = [False for _ in range(cabbage_num)]

    #모든 배추 위치 좌표를 돌며 인접한 배추 그룹 개수 찾기
    cabbage_group_num = 0
    for index, coordinate in enumerate(cabbage_coordinates):
        cabbage_group_num += find_cabbage_group(coordinate[0], coordinate[1], index, cabbage_coordinates, visited)

    #결과 리스트에 추가
    answer_list.append(cabbage_group_num)

#결과 출력
for answer in answer_list:
    print(answer)

틀렸습니다

수정된 코드

#백준 1012번

import sys
q_input = sys.stdin.readline
sys.setrecursionlimit(10**6)

#define dfs function: finding cabbage group
def dfs(cabbage_field:list, row:int, col:int) -> None:
    
    cabbage_field[row][col] = 0

    if row-1 >= 0 and cabbage_field[row-1][col] == 1:
        dfs(cabbage_field, row-1, col)
    if col-1 >= 0 and cabbage_field[row][col-1] == 1:
        dfs(cabbage_field, row, col-1)
    if col+1 <= column_count-1 and cabbage_field[row][col+1] == 1:
        dfs(cabbage_field, row, col+1)
    if row+1 <= row_count-1 and cabbage_field[row+1][col] == 1:
        dfs(cabbage_field, row+1, col)
    
#get a number of testcases
testcases_num = int(q_input())

#create answer_list
answer_list = []

#get column_count, row_count, cabbage_count of each testcases
for _ in range(testcases_num):
    column_count, row_count, cabbage_count = map(int, q_input().split())

    #initialize cabbage field
    cabbage_field = [[0 for _ in range(column_count)] for _ in range(row_count)]

    #get a location of cabbages and mark at cabbage field
    for _ in range(cabbage_count):
        j, i = map(int, q_input().split())
        cabbage_field[i][j] = 1

    #loop every location, count number of cabbage group
    cabbage_group_num = 0
    for i in range(row_count):
        for j in range(column_count):
            if cabbage_field[i][j] == 1:
                dfs(cabbage_field, i, j)
                cabbage_group_num += 1

    #append cabbage_group_num to answer_list
    answer_list.append(cabbage_group_num)

#print answer_list
for answer in answer_list:
    print(answer)

맞았습니다

profile
스타트업을 준비하는 대학생입니다.

0개의 댓글