본문 바로가기
Programming

백준_2667_단지번호 붙이기_dfs_bfs_파이썬

by WelcomeBro 2023. 8. 4.
반응형

문제 링크

 

2667번: 단지번호붙이기

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

www.acmicpc.net

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
size = int(input())
map1 = []
visited_map = [[False for _ in range(size)] for _ in range(size)]
for i in range(size):
    map1.append(list(map(int,list(input()))))
 
row_x = [1,-1,0,0]
col_y = [0,0,1,-1]
 
def dfs(row, col):
    global now_score
    if visited_map[row][col] == False and map1[row][col] == 1:
        now_score +=1
        visited_map[row][col] = True
        for i in range(4):
            now_x = row+row_x[i]
            now_y = col+col_y[i]
            if -1<now_x and now_x<size and -1<now_y and now_y<size:
                dfs(now_x,now_y)
    return now_score
 
def bfs(row,col):
    now_score = 0
    check_list = []
    if visited_map[row][col] == False and map1[row][col] == 1:
        visited_map[row][col] = True
        now_score += 1 
        check_list.append((row,col))
    while len(check_list)!=0:
        row,col = check_list.pop(0)
        for i in range(4):
            now_x = row+row_x[i]
            now_y = col+col_y[i]
            if -1<now_x and now_x<size and -1<now_y and now_y<size:
                if visited_map[now_x][now_y] == False and map1[now_x][now_y] == 1:
                    visited_map[now_x][now_y] = True
                    check_list.append((now_x,now_y))
                    now_score+=1
    return now_score
 
visited_map = [[False for _ in range(size)] for _ in range(size)]
 
score = []
now_score = 0
 
for i in range(size):
    for k in range(size):
        now_score = 0
        now_score = bfs(i,k)
        if now_score != 0:
            score.append(now_score)
score.sort()
print(len(score))
for i in score:
    print(i)
cs

 

Be positive!

Be rich!

Live your life!

반응형

'Programming' 카테고리의 다른 글

강화학습_4_0808  (0) 2023.08.08
백준_1012_유기농 배추_dfs_bfs_파이썬  (0) 2023.08.05
백준_1260_DFS와 BFS_0803  (0) 2023.08.03
강화학습_3_0802  (0) 2023.08.02
백준_2559_수열_파이썬  (0) 2023.08.01