[백준/Python] 2606. 바이러스

2024. 11. 27. 16:34·CODING_TEST

※ 문제

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

 

※ 문제 유형

그래프 이론, 그래프 탐색, 너비 우선 탐색, 깊이 우선 탐색(SILVER_3)

※ 나의 풀이

  • 인접 리스트를 통한 그래프 생성
  • BFS(너비 우선 탐색)
import sys
from collections import deque

N = int(sys.stdin.readline()) # 정점(Vertex)(노드) 수
M = int(sys.stdin.readline()) # 입력 그래프 쌍 수

graph = { i :[] for i in range(N + 1) }
# print(graph) # {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: []}


for i in range(M):
    vertex_1, vertex_2 = map(int, sys.stdin.readline().split())

    # 양방향 그래프
    graph[vertex_1].append(vertex_2)
    graph[vertex_2].append(vertex_1)

# print(graph) # {0: [], 1: [2, 5], 2: [1, 3, 5], 3: [2], 4: [7], 5: [1, 2, 6], 6: [5], 7: [4]}

visited = [False] * (N + 1)
ans = 0

# BFS : 너비 우선 탐색 (1 - 2 - 5 - 3 - 6)
def BFS(x): # x번 부터 BFS 실행
    que = deque()
    global ans # 감연된 컴퓨터 수
    que.append(x)
    visited[x] = True

    while que:
        n = que.popleft()
        for n_next in graph[n]:
            if not visited[n_next]: # 감염이 되지 않았다면
                visited[n_next] = True # 감염
                que.append(n_next) # 감염 리스트 추가
                ans += 1 # 감염된 컴퓨터 수 1 증가

BFS(1) # 1번에서 BFS 실행
# print(visited) [False, True, True, True, False, True, True, False]
print(ans)

 

'CODING_TEST' 카테고리의 다른 글

[프로그래머스/Python] 기사단원의 무기  (0) 2024.12.17
[프로그래머스/Python] 추억 점수  (0) 2024.12.17
[프로그래머스/Python] [1차] 비밀지도  (0) 2024.12.16
[백준/Python] 2910. 빈도 정렬  (1) 2024.11.26
[백준/Python] 1744. 수 묶기  (0) 2024.11.22
'CODING_TEST' 카테고리의 다른 글
  • [프로그래머스/Python] 추억 점수
  • [프로그래머스/Python] [1차] 비밀지도
  • [백준/Python] 2910. 빈도 정렬
  • [백준/Python] 1744. 수 묶기
YAHO_STUDY
YAHO_STUDY
DATA&AI_study.zip
  • YAHO_STUDY
    YAHO_CODE
    YAHO_STUDY
  • 전체
    오늘
    어제
    • 분류 전체보기 (57)
      • Paper Review (0)
      • SQL (16)
      • CODING_TEST (21)
      • Time Series (0)
      • DL (20)
        • NLP (5)
        • LLM&RAG (15)
        • Recommender System (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Lora
    PEFT
    qlora
    Gemma
    runpod
    SQL
    양자화
    fine-tuning
    coding_test
    한 권으로 끝내는 실전 llm 파인튜닝
    RNN
    prompt-tuning
    quantization
    hash
    graph
    MySQL
    Programmers
    DP
    boj
    pagedattention
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
YAHO_STUDY
[백준/Python] 2606. 바이러스
상단으로

티스토리툴바