1. ๋ฌธ์
2. ์ ์ถ๋ ฅ
3. ์ ์ถ๋ ฅ ์์
4. ๋ฌธ์ ์ค๊ณ
- ์ธ์ ๋ฆฌ์คํธ๋ก ๊ทธ๋ํ๋ฅผ ๊ตฌํํ๊ณ , ๋๋น ์ฐ์ ํ์์ ์งํํ๋ฉด์ ๊ฐ ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ ๋๋ง๋ค ์ธ์ ํ ๋ ธ๋์ ์์ด 0์ด๋ผ๋ฉด 1, 1์ด๋ผ๋ฉด 0์ ์น ํจ
- ์ธ์ ํ ๋ ธ๋๋ค์ ๋ํ ์์น ์ ๋ง์น๊ณ , ํ์ฌ๋ ธ๋์ ์ธ์ ํ ๋ ธ๋ ์ค ๊ฐ์ ์์ด ์์ผ๋ฉด 2์ ์์น ํ๊ธฐ๊ฐ ๋ถ๊ฐ๋ฅํ ๊ฒ์ ์ ์ ์์
- ๋ฐ๋ผ์ O(N + M)์ ์๊ฐ๋ณต์ก๋๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์
5. ์ ์ฒด ์ฝ๋
//MARK: - 2์์น ํ๊ธฐ - BFS
//MARK: - Framework
import Foundation
//MARK: - Type
struct Graph {
//MARK: - Property
var edges: [Int]
//MARK: - Initializer
init() {
self.edges = []
}
}
//MARK: - Variable
var graph: [Graph] = []
var visited: [Bool] = []
var groups: [Int] = []
//MARK: - Function
func bfs(_ start: Int) -> Bool {
var result: Bool = true
var queue: [Int] = []
queue.append(start)
visited[start] = true
while !queue.isEmpty {
let current: Int = queue.removeFirst()
for i in stride(from: 0, to: graph[current].edges.count, by: 1) {
let next: Int = graph[current].edges[i]
if !visited[next] {
groups[next] = groups[current] == 0 ? 1 : 0
visited[next] = true
queue.append(next)
}
if groups[next] == groups[current] {
result = false
break
}
}
if !result {
break
}
}
return result
}
func solution() -> Void {
//MARK: - Input
guard let input = readLine()?.components(separatedBy: " ") else { return }
let N: Int = input.map { Int($0) }[0] ?? 0
let M: Int = input.map { Int($0) }[1] ?? 0
graph = Array(repeating: Graph(), count: N + 10)
visited = Array(repeating: false, count: N + 10)
groups = Array(repeating: 0, count: N + 10)
for _ in 0..<M {
guard let data = readLine()?.components(separatedBy: " ") else { return }
let a: Int = data.map { Int($0) }[0] ?? 0
let b: Int = data.map { Int($0) }[1] ?? 0
graph[a].edges.append(b)
graph[b].edges.append(a)
}
//MARK: - Process & Output
print(bfs(0) ? "YES" : "NO")
}
solution()
์ ์ฒด์ฝ๋๋ ์ฌ๊ธฐ์์ ํ์ธํ ์ ์์ต๋๋ค.
'Swift Data Structure And Algorithm > Graph Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ ๋ฐ์ด๋ฌ์ค_BFS (0) | 2022.04.15 |
---|---|
์ด๋ถ ๊ทธ๋ํ ํ๋ณ_BFS (0) | 2022.04.15 |
๊น์ด์ฐ์ ํ์๊ณผ ๋๋น์ฐ์ ํ์ (0) | 2022.04.15 |
๋จ์ง ๋ฒํธ ๋ถ์ด๊ธฐ_DFS (0) | 2022.04.15 |
์ ๋ฐ์ด๋ฌ์ค_DFS (0) | 2022.04.15 |