๐Ÿ  ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

๋ฐฑ์ค€ Class3 Silver1

solved_ac[Class3] ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

๋ฌธ์ œ

<๊ทธ๋ฆผ 1>๊ณผ ๊ฐ™์ด ์ •์‚ฌ๊ฐํ˜• ๋ชจ์–‘์˜ ์ง€๋„๊ฐ€ ์žˆ๋‹ค. 1์€ ์ง‘์ด ์žˆ๋Š” ๊ณณ์„, 0์€ ์ง‘์ด ์—†๋Š” ๊ณณ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค. ์ฒ ์ˆ˜๋Š” ์ด ์ง€๋„๋ฅผ ๊ฐ€์ง€๊ณ  ์—ฐ๊ฒฐ๋œ ์ง‘์˜ ๋ชจ์ž„์ธ ๋‹จ์ง€๋ฅผ ์ •์˜ํ•˜๊ณ , ๋‹จ์ง€์— ๋ฒˆํ˜ธ๋ฅผ ๋ถ™์ด๋ ค ํ•œ๋‹ค. ์—ฌ๊ธฐ์„œ ์—ฐ๊ฒฐ๋˜์—ˆ๋‹ค๋Š” ๊ฒƒ์€ ์–ด๋–ค ์ง‘์ด ์ขŒ์šฐ, ํ˜น์€ ์•„๋ž˜์œ„๋กœ ๋‹ค๋ฅธ ์ง‘์ด ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ๋งํ•œ๋‹ค. ๋Œ€๊ฐ์„ ์ƒ์— ์ง‘์ด ์žˆ๋Š” ๊ฒฝ์šฐ๋Š” ์—ฐ๊ฒฐ๋œ ๊ฒƒ์ด ์•„๋‹ˆ๋‹ค. <๊ทธ๋ฆผ 2>๋Š” <๊ทธ๋ฆผ 1>์„ ๋‹จ์ง€๋ณ„๋กœ ๋ฒˆํ˜ธ๋ฅผ ๋ถ™์ธ ๊ฒƒ์ด๋‹ค. ์ง€๋„๋ฅผ ์ž…๋ ฅํ•˜์—ฌ ๋‹จ์ง€์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๊ณ , ๊ฐ ๋‹จ์ง€์— ์†ํ•˜๋Š” ์ง‘์˜ ์ˆ˜๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜์—ฌ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

img

์ž…๋ ฅ

์ฒซ ๋ฒˆ์งธ ์ค„์—๋Š” ์ง€๋„์˜ ํฌ๊ธฐ N(์ •์‚ฌ๊ฐํ˜•์ด๋ฏ€๋กœ ๊ฐ€๋กœ์™€ ์„ธ๋กœ์˜ ํฌ๊ธฐ๋Š” ๊ฐ™์œผ๋ฉฐ 5โ‰คNโ‰ค25)์ด ์ž…๋ ฅ๋˜๊ณ , ๊ทธ ๋‹ค์Œ N์ค„์—๋Š” ๊ฐ๊ฐ N๊ฐœ์˜ ์ž๋ฃŒ(0ํ˜น์€ 1)๊ฐ€ ์ž…๋ ฅ๋œ๋‹ค.

์ถœ๋ ฅ

์ฒซ ๋ฒˆ์งธ ์ค„์—๋Š” ์ด ๋‹จ์ง€์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์˜ค. ๊ทธ๋ฆฌ๊ณ  ๊ฐ ๋‹จ์ง€๋‚ด ์ง‘์˜ ์ˆ˜๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜์—ฌ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ถœ๋ ฅํ•˜์‹œ์˜ค.

์˜ˆ์ œ ์ž…๋ ฅ 1

7
0110100
0110101
1110101
0000111
0100000
0111110
0111000

์˜ˆ์ œ ์ถœ๋ ฅ 1

3
7
8
9

๐Ÿ›  ์ž๋ฃŒ๊ตฌ์กฐ

BFS๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ’€์—ˆ๋‹ค. ํŠน์ • 1 ๋…ธ๋“œ๋ฅผ ๊ธฐ์ ์œผ๋กœ ํ•˜์—ฌ ๋” ์ด์ƒ 1์ด ์•ˆ ๋‚˜์˜ฌ๋•Œ๊นŒ์ง€ ์™„์ „ํƒ์ƒ‰์„ ํ•˜๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— DFS,BFS ๋ฌด์—‡์„ ์„ ํƒํ•˜๋“  ์ƒ๊ด€ ์—†์—ˆ๋‹ค.

๋‚˜๋Š” visited ๋ฐฐ์—ด์„ ๋”ฐ๋กœ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ž˜ํ”„ ์ž์ฒด ๋‚ด์—์„œ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

แ„‹แ…งแ†ซแ„‰แ…ณแ†ธแ„Œแ…กแ†ผ-5

๋งˆ์ง€๋ง‰ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ๊นŒ์ง€ ๊ณ ๋ คํ•˜์—ฌ ์ง‘ 9๊ฐœ๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜์˜€๋‹ค.

๊ทธ๋ž˜ํ”„์˜ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€ 1์ธ ๋…ธ๋“œ๋“ค์„ ํƒ์ƒ‰ํ•˜๋ฉฐ 2๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค. ๊ทธ๋ฆฌ๊ณ  BFSํƒ์ƒ‰์ด ์ข…๋ฃŒ๋˜์—ˆ์œผ๋ฉด ์ตœ์ข… ์ง‘์˜ ๊ฐœ์ˆ˜๋ฅผ ์ •๋‹ต ๋ฐฐ์—ด์— ์ถ”๊ฐ€ํ•œ๋‹ค.

๊ทธ๋ ‡๊ฒŒ ํ•ด์„œ ๋‚˜์˜จ ์ •๋‹ต ๋ฐฐ์—ด์„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์„ ์‹œํ‚จ ํ›„, ์ •๋‹ต์„ ํ˜•์‹์— ๋งž๊ฒŒ ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป CODE

from collections import deque

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

for i in range(n):
    house_info = input()
    for j in range(n):
        graph[i][j] = int(house_info[j])

def bfs(x,y):
    house_count = 0
    q = deque([[x,y]])
    graph[x][y] = 2
    while q:
        cur_node = q.popleft()
        house_count += 1

        for i in range(4):
            new_x = cur_node[0]+dx[i]
            new_y = cur_node[1]+dy[i]

            if 0<=new_x<n and 0<=new_y<n:
                if graph[new_x][new_y] == 1:
                    q.append([new_x,new_y])
                    graph[new_x][new_y] = 2
    
    return house_count

lst_answer = []

for x in range(n):
    for y in range(n):
        if graph[x][y] == 1:
            lst_answer.append(bfs(x,y))
lst_answer.sort()
print(len(lst_answer))
for answer in lst_answer:
    print(answer)

ยฉ 2022. All rights reserved.

Powered by Hydejack v9.1.6