๐Ÿ”Ž ๊ฒฝ๋กœ ์ฐพ๊ธฐ

๋ฐฑ์ค€ Class3 Silver1

solved_ac[Class3] ๊ฒฝ๋กœ ์ฐพ๊ธฐ

๋ฌธ์ œ

๊ฐ€์ค‘์น˜ ์—†๋Š” ๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„ G๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ชจ๋“  ์ •์  (i, j)์— ๋Œ€ํ•ด์„œ, i์—์„œ j๋กœ ๊ฐ€๋Š” ๊ฒฝ๋กœ๊ฐ€ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N (1 โ‰ค N โ‰ค 100)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ ์ค„์—๋Š” ๊ทธ๋ž˜ํ”„์˜ ์ธ์ ‘ ํ–‰๋ ฌ์ด ์ฃผ์–ด์ง„๋‹ค. i๋ฒˆ์งธ ์ค„์˜ j๋ฒˆ์งธ ์ˆซ์ž๊ฐ€ 1์ธ ๊ฒฝ์šฐ์—๋Š” i์—์„œ j๋กœ ๊ฐ€๋Š” ๊ฐ„์„ ์ด ์กด์žฌํ•œ๋‹ค๋Š” ๋œป์ด๊ณ , 0์ธ ๊ฒฝ์šฐ๋Š” ์—†๋‹ค๋Š” ๋œป์ด๋‹ค. i๋ฒˆ์งธ ์ค„์˜ i๋ฒˆ์งธ ์ˆซ์ž๋Š” ํ•ญ์ƒ 0์ด๋‹ค.

์ถœ๋ ฅ

์ด N๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ์„œ ๋ฌธ์ œ์˜ ์ •๋‹ต์„ ์ธ์ ‘ํ–‰๋ ฌ ํ˜•์‹์œผ๋กœ ์ถœ๋ ฅํ•œ๋‹ค. ์ •์  i์—์„œ j๋กœ ๊ฐ€๋Š” ๊ฒฝ๋กœ๊ฐ€ ์žˆ์œผ๋ฉด i๋ฒˆ์งธ ์ค„์˜ j๋ฒˆ์งธ ์ˆซ์ž๋ฅผ 1๋กœ, ์—†์œผ๋ฉด 0์œผ๋กœ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

์˜ˆ์ œ ์ž…๋ ฅ 1

3
0 1 0
0 0 1
1 0 0

์˜ˆ์ œ ์ถœ๋ ฅ 1

1 1 1
1 1 1
1 1 1

์˜ˆ์ œ ์ž…๋ ฅ 2

7
0 0 0 1 0 0 0
0 0 0 0 0 0 1
0 0 0 0 0 0 0
0 0 0 0 1 1 0
1 0 0 0 0 0 0
0 0 0 0 0 0 1
0 0 1 0 0 0 0

์˜ˆ์ œ ์ถœ๋ ฅ 2

1 0 1 1 1 1 1
0 0 1 0 0 0 1
0 0 0 0 0 0 0
1 0 1 1 1 1 1
1 0 1 1 1 1 1
0 0 1 0 0 0 1
0 0 1 0 0 0 0

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

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

Visited ๋ฐฐ์—ด โžก๏ธ index ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜์˜€๋Š”์ง€๋ฅผ ์•Œ๋ ค์ฃผ๋Š” ๋ฐฐ์—ด

์ด ๋ฌธ์ œ๊ฐ€ ๋ฌป๊ณ ์ž ํ•˜๋Š” ์š”์ง€๋ฅผ ํ•œ ๋งˆ๋””๋กœ ์ •๋ฆฌํ•˜๋ฉด

โ€œํŠน์ • ๋…ธ๋“œ๋กœ๋ถ€ํ„ฐ ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•˜์˜€์„ ๋•Œ, ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ๋…ธ๋“œ๋Š”?โ€

๋”ฐ๋ผ์„œ, 0๋ฒˆ ๋…ธ๋“œ๋ถ€ํ„ฐ N-1๋ฒˆ ๋…ธ๋“œ๊นŒ์ง€ ๊ฐ๊ฐ ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰์„ ํ•˜์—ฌ Visited ๋ฐฐ์—ด์„ ๋ฝ‘์•„์ฃผ๋ฉด ๋œ๋‹ค.

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

from collections import deque

N = int(input())
graph = [[0]*N for _ in range(N)]

for i in range(N):
    line = input().replace(" ","")
    for j in range(N):
        graph[i][j] = int(line[j])

def bfs(start):
    visited = [0]*N
    q = deque([start])

    while q:
        cur = q.popleft()

        for i in range(N):
            if graph[cur][i] == 1 and visited[i] == 0:
                q.append(i)
                visited[i] = 1
    
    return visited

for node in range(N):
    print(*bfs(node))

ยฉ 2022. All rights reserved.

Powered by Hydejack v9.1.6