[Python] 백준 2667 - 단지번호붙이기

2021. 11. 6. 13:19·IT/알고리즘
반응형

문제

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

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

문제 해결방법

bfs 로 해결 가능

graph[i][j] 가 1인 곳에서 검색을 시작해서
인접한 부분을 찾고 종료시 count return

문제 풀이

import sys
from collections import deque

N = int(sys.stdin.readline().strip())
boards = []
for _ in range(N):
    boards.append(list(map(int, sys.stdin.readline().strip())))

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


def bfs(x, y):
    queue = deque()
    queue.append((x, y))
    boards[x][y] = 0
    count = 1

    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= N or ny < 0 or ny >= N:
                continue
            if boards[nx][ny] == 1:
                boards[nx][ny] = 0
                queue.append((nx, ny))
                count += 1
    return count


result = []
for i in range(N):
    for j in range(N):
        if boards[i][j] == 1:
            result.append(bfs(i, j))

result.sort()
print(len(result))
for r in result:
    print(r)

 

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)
'IT/알고리즘' 카테고리의 다른 글
  • [Python] 백준 7576 - 토마토
  • [Python] 백준 1012 - 유기농 배추
  • 프로그래머스 - 가장 큰 정사각형 찾기
  • 프로그래머스 - 나머지 한 점
상쾌한기분
상쾌한기분
  • 상쾌한기분
    상쾌한기분
    상쾌한기분
  • 전체
    오늘
    어제
    • 분류 전체보기 (251)
      • Python (44)
        • Python (26)
        • Django (6)
        • Flask (4)
        • Open Source (6)
      • Kotlin & Java (5)
        • Spring (2)
        • 프로젝트 (1)
      • Go (11)
      • Database (24)
        • MySQL (21)
        • Redis (3)
      • Infrastructure (2)
        • CDC (4)
        • Kafka (5)
        • Prometheus (2)
        • Fluentd (11)
        • Docker (1)
        • Airflow (2)
        • VPN (2)
      • IT (26)
        • AI (9)
        • Langchain (8)
        • Web (18)
        • Git (8)
        • 리팩토링 (9)
        • Micro Service Architecture (8)
        • Clean Code (16)
        • Design Pattern (0)
        • 수학 (1)
        • 알고리즘 (14)
      • OS (14)
        • Centos (10)
        • Ubuntu (3)
        • Mac (1)
      • Search Engine (2)
        • ElasticSearch (1)
        • Lucene Solr (1)
      • PHP (2)
        • Laravel (1)
        • Codeigniter (1)
  • 블로그 메뉴

    • Github 방문
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    fluentd
    prompt
    Golang
    performance
    Redis
    MYSQL
    Kafka
    백준
    python
    CDC
    docker
    티스토리챌린지
    http
    파이썬
    Langchain
    git
    오블완
    ollama
    LLM
    go
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
상쾌한기분
[Python] 백준 2667 - 단지번호붙이기
상단으로

티스토리툴바