๋ฐฑ์ค€ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/DFS & BFS

[๋ฐฑ์ค€ 2667] [dfs/bfs] ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

_cactus 2021. 4. 23. 23:35
๋ฐ˜์‘ํ˜•

๐Ÿ’ป ๋ฐฑ์ค€ 2667๋ฒˆ [๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ]

ํ’€์ด)

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

visited = [[0]*n for _ in range(n)]
cnt_lst = []
cnt = 0
def dfs(x,y) :
    global cnt 
    # 1. ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ์ธ์ง€ ํ™•์ธ
    if not visited[x][y] :
        # ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
        visited[x][y] = 1 
        if map_[x][y] == 0 : return # !!!!!!!!!!!!!!!!!!!!!!!!!!!์ด๊ฑฐ ํ•œ์ค„ ์•ˆํ•ด์„œ ํ‹€๋ ธ์—ˆ์Œ
        # 2. ์ธ์ ‘๋…ธ๋“œ ์ˆœํšŒ
        for [i,j] in [[x+1,y],[x,y+1],[x-1,y],[x,y-1]] :
            if 0 <= i <= n-1 and 0 <= j <= n-1 : 
                if map_[i][j] == 1 and not visited[i][j]:
                    cnt += 1 
                    dfs(i,j)
                elif map_[i][j] == 0 :
                    visited[i][j] = 1 
    return

for i in range(n) :
    for j in range(n) :
        if not visited[i][j] : 
            if map_[i][j] == 1 : cnt = 1
            else : cnt = 0
            dfs(i,j)
            if cnt != 0 : cnt_lst.append(cnt)

print(len(cnt_lst))
print(*sorted(cnt_lst),sep='\n')

 

๋ฉ”๋ชจ๋ฆฌ ์‹œ๊ฐ„ ์–ธ์–ด ์ฝ”๋“œ๊ธธ์ด
29396KB 68ms Python 3 919B

 

 

728x90
๋ฐ˜์‘ํ˜•