반응형
문제
https://www.acmicpc.net/problem/2644
풀이
전형적인 그래프 문제이다.
문제에서는 촌수를 계산하고 머 어렵지 않게 써놨지만,
이 문제는 모든 간선의 비용이 1인 노드사이의 거리를 출력하라는 것과 동일하다.
DFS, 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 n = Int(readLine()!)! | |
let input = readLine()!.split { $0 == " " }.map { Int($0)! } | |
let a = input[0], b = input[1] | |
let m = Int(readLine()!)! | |
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) | |
graph[b].append(a) | |
} | |
var queue = [(a, 0)] | |
var index = 0 | |
var answer = -1 | |
while queue.count > index { | |
let current = queue[index] | |
let node = current.0 | |
let d = current.1 | |
visited[node] = true | |
if node == b { | |
answer = d | |
break | |
} | |
for nextNode in graph[node] { | |
if !visited[nextNode] { | |
visited[nextNode] = true | |
queue.append((nextNode, d + 1)) | |
} | |
} | |
index += 1 | |
} | |
print(answer) |
후기
어렵지 않게 풀 수 있는 문제였다.
챌린저 문제를 풀었어야 하는데.. 여러번 시간이 없다는 핑계로 안풀고 있다.
내일이랑 모레도 바쁠텐데 꼭 풀어보려고 노력해야지.
반응형
'TIL > 코테 스터디' 카테고리의 다른 글
99클럽 코테 스터디 10일차 TIL: 방향 그래프 (0) | 2024.11.06 |
---|---|
99클럽 코테 스터디 9일차 TIL: BFS (2) | 2024.11.05 |
99클럽 코테 스터디 7일차 TIL: 트리 (1) | 2024.11.03 |
99클럽 코테 스터디 6일차 TIL: 그래프 (1) | 2024.11.02 |
99클럽 코테 스터디 5일차 TIL: BFS (1) | 2024.11.01 |