๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“š Algorithm/Baekjoon

[Baekjoon] ๋ฐฑ์ค€ 2667 '๋‹จ์ง€ ๋ฒˆํ˜ธ ๋ถ™์ด๊ธฐ' ๋ฌธ์ œํ’€์ด ํŒŒ์ด์ฌ, Python, ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ •๋ฆฌ

๐Ÿ“ 2667 ๋ฌธ์ œ

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

 

 

์ž…๋ ฅ

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

 

์ถœ๋ ฅ

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

 

 

๐Ÿง ํ’€์ด

๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ ๊ธฐ๋ฒ• ์ค‘ ํ•˜๋‚˜์ธ Depth First Search ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค. 

 

N = int(input())
graph = []
result = []
count = 0

for _ in range(N):
    graph.append(list(map(int, input().rstrip())))

xx = [0, 0, 1, -1]
yy = [1, -1, 0, 0]

def dfs(x, y) :
    
    global count
    if x < 0 or x >= N or y < 0 or y >= N:
       return 
    
    if graph[x][y] == 1 :
        count += 1
        graph[x][y] = 0
        for i in range(4) :
            nx = x + xx[i]
            ny = y + yy[i]
            dfs(nx, ny)

for i in range(N) :
    for j in range(N) :
        if graph[i][j] == 1 :
            dfs(i, j)
            result.append(count)
            count = 0

result.sort()
print(len(result))
for i in result :
    print(i)
728x90