Skip to content

Commit 3e665e8

Browse files
committed
[BOJ] #1976.여행가자 / 골드4 / 90(X)
1 parent ec2d8e1 commit 3e665e8

File tree

1 file changed

+34
-54
lines changed

1 file changed

+34
-54
lines changed
Lines changed: 34 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,40 @@
1-
'''
2-
3 > 도시의 수 N
3-
3 > 여행 계획에 속한 도시의 수 M
4-
5-
> NxN 행렬 (N개의 줄에 N개의 정수)
6-
0 1 0 1번 도시는 2번 도시와 연결
7-
1 0 1 2번 도시는 1,3번 도시와 연결
8-
0 1 0 3번 도시는 2번 도시와 연결
9-
10-
i 번째 줄의 j번째 수 (i, j)는 i번째 도시에서 j번째 도시의 연결 정보 (i-j)
11-
-> (i, j) = (j, i)
12-
1이면 연결, 0이면 연결 X
13-
같은 도시 여러번 방문 가능
14-
15-
1 2 3 > 여행 계획 (1번->2번->3번)
16-
1-2-3 => 모두 연결되어 있어서 YES
17-
'''
18-
191
import sys
202
input = sys.stdin.readline
213

224
N = int(input().strip()) # 도시의 수
235
M = int(input().strip()) # 여행 계획에 속한 도시의 수
246

25-
# 도시의 연결 정보
26-
graph = []
27-
for _ in range(N):
28-
graph.append(list(map(int, input().split()))) # NxN 행렬
29-
30-
plan = list(map(int, input().split())) # 여행 계획
31-
32-
'''
33-
그래서 어떻게..??
34-
여행계획에 속한 도시들이 모두 연결되어있는지를 확인
35-
-> 첫번째 도시에서 출발해서 다음 도시로 이동하는지 하나씩 확인..?
36-
'''
37-
def travel():
38-
for i in range(M-1): # (M-1)번 반복하면서 현재 도시에서 다음 도시로 이동 가능 여부 확인
39-
current_city = plan[i]-1 # 현재 도시
40-
next_city = plan[i+1]-1 # 다음 도시
41-
42-
if graph[current_city][next_city] == 0: # 이동할 수 없는 경우
43-
return 'NO'
44-
45-
return 'YES'
46-
47-
print(travel())
48-
'''
49-
아 이렇게 하면 근데 경유 하는 경우 고려를 못함.. 아 아닌가/?
50-
4
51-
3
52-
0 0 1 0
53-
0 0 0 1
54-
1 0 0 0
55-
0 1 0 0
56-
1 2 4
57-
일때 No
58-
59-
여러번 방문이 가능
60-
'''
7+
# 유니온 파인드 부모 배열
8+
parent = [i for i in range(N)]
9+
10+
# find 연산: 경로 압축을 이용하여 루트 노드 찾기
11+
def find(x):
12+
if parent[x] != x:
13+
parent[x] = find(parent[x])
14+
return parent[x]
15+
16+
# union 연산: 두 집합을 합치기
17+
def union(x, y):
18+
root_x = find(x)
19+
root_y = find(y)
20+
if root_x != root_y:
21+
parent[root_y] = root_x # y의 루트를 x로 연결
22+
23+
# 도시 연결 정보 처리
24+
for i in range(N):
25+
row = list(map(int, input().split()))
26+
for j in range(N):
27+
if row[j] == 1: # 두 도시가 연결된 경우
28+
union(i, j)
29+
30+
# 여행 계획 입력
31+
plan = list(map(int, input().split()))
32+
33+
# 여행 경로가 같은 집합인지 확인
34+
root = find(plan[0] - 1) # 첫 번째 도시의 루트
35+
for city in plan[1:]:
36+
if find(city - 1) != root:
37+
print("NO")
38+
exit()
39+
40+
print("YES")

0 commit comments

Comments
 (0)