220v
젝무의 개발새발
220v
전체 방문자
오늘
어제
  • 분류 전체보기 (255)
    • AI (35)
      • ML, DL 학습 (30)
      • 논문 리뷰 (4)
      • 실습 및 프로젝트 (1)
    • Algorithm (145)
      • LeetCode (13)
      • 프로그래머스 (35)
      • 백준 (96)
      • 알고리즘, 문법 정리 (1)
    • Mobile, Application (17)
      • Flutter (10)
      • iOS, MacOS (7)
    • BackEnd (7)
      • Flask (1)
      • Node.js (5)
      • Spring, JSP..etc (1)
    • Web - FrontEnd (18)
      • JavaScript, JQuery, HTML, C.. (12)
      • React (6)
    • DataBase (1)
      • MySQL (1)
      • Firebase Firestore (0)
      • Supabase (0)
    • Git (1)
    • 기타 툴 및 오류 해결 (3)
    • 강의 (5)
      • Database (3)
      • 암호학 (2)
      • 알고리즘 (0)
    • 후기와 회고 (2)
    • 블로그 꾸미기 (1)
    • 일상과 이것저것 (20)
      • 맛집 (12)
      • 세상사는일 (4)
      • 도서리뷰 (1)
      • 이런저런 생각들 (잡글) (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • REACT
  • binary search
  • 백준
  • dfs
  • Priority Queue
  • 다익스트라
  • two pointer
  • disjoint set
  • union-find
  • simulation
  • 위상 정렬
  • Greedy
  • IMPLEMENT
  • Prefix Sum
  • Mathematics
  • Minimum Spanning Tree
  • dp
  • 프로그래머스
  • topological sort
  • 티스토리챌린지
  • implementation
  • BFS
  • Dynamic Programming
  • Backtracking
  • brute-Force
  • Lis
  • top-down
  • 오블완
  • bitmasking
  • 구현

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/백준

[백준] 1012. 유기농 배추 - 파이썬

2023. 3. 26. 00:57

https://www.acmicpc.net/problem/1012

 

풀이

[백준 3197 - 백조의 호수], [백준 7569 - 토마토] 문제와 유사했던 문제.

마찬가지로, BFS를 이용해 풀이.

 

배추밭을 2차원 배열로 초기화, 이후 입력된 배추의 좌표를 가지고 2차원배열에 적용.

매 반복마다, 배추가 없는 지 확인.

배추가 있다면, 제일 먼저 발견된 배추를 Queue에 넣고, 먹어치워진 배추의 상하좌우를 탐색하며 BFS를 이용해 탐색을 진행.

인접한 모든 배추를 처리하고 나서, 다시 다음 반복을 진행~

복잡한 건 없어서 주석 이외 부가 설명은 필요하지 않은 듯.. ^ㅁ^

from collections import deque
test_case_cnt = int(input())
# 결과값 저장
worms = []

# 배추의 좌표를 임시 저장하는 변수
cab = []

# 배추가 싹 사라졌나요??
def isCabClear():
    for y, row in enumerate(field):
        for x, c in enumerate(row):
            if c == 1:
                cab.append([x, y])
                return False
    return True


for _ in range(test_case_cnt):
    worm_cnt = 0
    row, col, cab_num = map(int, input().split())

    # 배추밭 생성 뿅! 좌표는 x=3, y=4라면 field[4][3]처럼 접근해야 함! (column이 바깥쪽 차원)
    field = [[0]*row for _ in range(col)]

    # 배추를 심자 쏙쏙
    for _ in range(cab_num):
        r, c = map(int, input().split())
        field[c][r] = 1

    # 지렁이 마리수
    worm_cnt = 0

    # 먹을 배추~ (BFS에서의 Queue)
    deq = deque([])

    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

    while not isCabClear():
        deq.append(cab.pop())
        while deq:
            x, y = deq.popleft()
            field[y][x] = 0
            for i in range(4):
                nx = x+dx[i]
                ny = y+dy[i]

                # 밭의 경계(M, N)을 벗어나지 않고, 배추가 있다면
                if 0 <= nx < row and 0 <= ny < col and field[ny][nx] == 1:
                    # 배추 먹고 큐에 추가
                    field[ny][nx] = 0
                    deq.append([nx, ny])

        worm_cnt += 1
    worms.append(worm_cnt)

for cnt in worms:
    print(cnt)

 

 

    'Algorithm/백준' 카테고리의 다른 글
    • [백준] 1074. Z - 파이썬
    • [백준] 1003. 피보나치 함수 - 파이썬
    • [백준] 7569. 토마토 - 파이썬
    • [백준] 2281. 데스노트 - 파이썬
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바