반응형
벌써 10일차라니.. 시간 정말 빠르다.
문제
https://www.acmicpc.net/problem/18352
풀이
이 문제는 99클럽 코테 스터디 중에 등장한 적 없었던 방향 그래프 문제이다.
여태 무방향 그래프 문제만 나왔었는데, 이번엔 방향 그래프 문제가 나왔다.
사실 방향 그래프라고 해서 뭐 대단한 것은 없고
말 그대로 간선에 방향이 있는 것이다.
이 문제에서는 x노드에서 최단 거리가 k인 노드들을 찾는 문제이다.
최단 거리를 찾는 것이므로, BFS 알고리즘을 사용해서 풀 수 있었다.
간선의 비용이 동일할 때 최단거리임을 보장하기 때문이다.
소스코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let input = readLine()!.split { $0 == " " }.map { Int($0)! } | |
let n = input[0], m = input[1], k = input[2], x = input[3] | |
var graph = [[Int]](repeating: [], count: n + 1) | |
var visited = [Bool](repeating: false, count: n + 1) | |
for _ in 0..<m { | |
let input = readLine()!.split { $0 == " " }.map { Int($0)! } | |
let a = input[0], b = input[1] | |
graph[a].append(b) | |
} | |
var queue = [(x, 0)] | |
var index = 0 | |
var result: [Int] = [] | |
while queue.count > index { | |
let currentNode = queue[index].0 | |
let cost = queue[index].1 | |
visited[currentNode] = true | |
if cost == k { | |
result.append(currentNode) | |
} | |
for nextNode in graph[currentNode] { | |
if !visited[nextNode] { | |
visited[nextNode] = true | |
queue.append((nextNode, cost + 1)) | |
} | |
} | |
index += 1 | |
} | |
print(result.isEmpty ? -1 : result.sorted().map { String($0) }.joined(separator: "\n")) |
후기
BFS 알고리즘에 이해가 있다면 쉽게 풀 수 있는 문제였다.
반응형
'TIL > 코테 스터디' 카테고리의 다른 글
99클럽 코테 스터디 12일차 TIL: 3차원 그래프 (0) | 2024.11.08 |
---|---|
99클럽 코테 스터디 11일차 TIL: DFS (2) | 2024.11.07 |
99클럽 코테 스터디 9일차 TIL: BFS (2) | 2024.11.05 |
99클럽 코테 스터디 8일차 TIL: 그래프 (0) | 2024.11.04 |
99클럽 코테 스터디 7일차 TIL: 트리 (1) | 2024.11.03 |