happyso
study with happyso
happyso
전체 방문자
오늘
어제
  • 분류 전체보기 (300)
    • GIT (3)
    • 컴퓨터 기본 개념 (29)
    • 알고리즘 (125)
      • 알고리즘 문제 (115)
      • 알고리즘 개념 (10)
    • Go (2)
    • 클라우드 (53)
      • DevOps (3)
      • Kubernetes(쿠버네티스) (33)
      • AWS (6)
      • CKA (8)
    • 리눅스(Linux) (18)
      • 컨테이너(Container) (8)
    • Front (22)
      • JavaScript (2)
      • React (20)
    • Python (21)
      • Python 웹 크롤링 (11)
      • Django (7)
      • MachineLearning (3)
    • 데이터베이스 (6)
      • MariaDB (2)
      • MongoDB (4)
    • C언어 (5)
    • Trouble Shooting (2)
    • 네트워크 (8)
      • CCNA (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • edit
  • kubernetes
  • 15
  • 18
  • Patch
  • replace
  • apply

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
happyso

study with happyso

[python] 백준 > dfs > 단지번호 붙히기
알고리즘/알고리즘 문제

[python] 백준 > dfs > 단지번호 붙히기

2021. 1. 14. 02:14

[문제]

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

 

 

 

 

 

www.acmicpc.net/problem/2667

 

2667번: 단지번호붙이기

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

www.acmicpc.net

[나의 풀이-bfs]

from collections import deque, Counter
from functools import reduce

n = int(input())
a = [list(map(int, input())) for _ in range(n)]

dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
check = [[0]*n for _ in range(n)]


def bfs(x, y, cnt):
    q = deque()
    q.append([x, y])
    check[x][y] = cnt
    while q:
        x, y = q.popleft()
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < n and 0 <= ny < n:
                if a[nx][ny] == 1 and check[nx][ny] == 0:
                    q.append([nx, ny])
                    check[nx][ny] = cnt


cnt = 0
for i in range(n):
    for j in range(n):
        if a[i][j] == 1 and check[i][j] == 0:
            cnt += 1
            bfs(i, j, cnt)
print(cnt)
print('------------------------------')
print(check)
print('------------------------------')
answer = reduce(lambda x, y: x+y, check)
print(answer)
print('------------------------------')
answer = [x for x in answer if x > 0]
print(answer)
print('------------------------------')
answer = sorted(list(Counter(answer).values()))
print('\n'.join(map(str, answer)))
print('------------------------------')

 

[나의 풀이-dfs]

n = int(input())
a = [list(map(int, input())) for _ in range(n)]

dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
check = [[0]*n for _ in range(n)]
answer = []


def dfs(x, y):
    global cnt
    cnt += 1
    check[x][y] = 1

    for i in range(4):
        nx, ny = x+dx[i], y+dy[i]
        if 0 <= nx < n and 0 <= ny < n:
            if a[nx][ny] == 1 and check[nx][ny] == 0:
                dfs(nx, ny)


for i in range(n):
    for j in range(n):
        if a[i][j] == 1 and check[i][j] == 0:
            cnt = 0
            dfs(i, j)
            answer.append(cnt)

print(len(answer))
answer.sort()
print('\n'.join(map(str, answer)))

 

'알고리즘 > 알고리즘 문제' 카테고리의 다른 글

[python] 백준 > 괄호  (0) 2021.01.15
[python] 백준 > DFS > ABCDE  (0) 2021.01.14
[python] 프로그래머스 > 시저암호  (0) 2021.01.13
[python] 프로그래머스 > 3진법 뒤집기  (0) 2021.01.12
[python] 프로그래머스 > 모의고사  (0) 2021.01.11
    '알고리즘/알고리즘 문제' 카테고리의 다른 글
    • [python] 백준 > 괄호
    • [python] 백준 > DFS > ABCDE
    • [python] 프로그래머스 > 시저암호
    • [python] 프로그래머스 > 3진법 뒤집기
    happyso
    happyso

    티스토리툴바