forked from banjodayo39/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IsGraphBipartite.swift
37 lines (30 loc) · 990 Bytes
/
IsGraphBipartite.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Question Link: https://leetcode.com/problems/is-graph-bipartite/
* Primary idea: Depth-first Search, try to color the graph with two colors
*
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class IsGraphBipartite {
func isBipartite(_ graph: [[Int]]) -> Bool {
var colors = Array(repeating: -1, count: graph.count)
for i in 0..<graph.count {
if colors[i] == -1 && !validColor(&colors, 0, graph, i) {
return false
}
}
return true
}
fileprivate func validColor(_ colors: inout [Int], _ color: Int, _ graph: [[Int]], _ index: Int) -> Bool {
if colors[index] != -1 {
return colors[index] == color
}
colors[index] = color
for neighbor in graph[index] {
if !validColor(&colors, 1 - color, graph, neighbor) {
return false
}
}
return true
}
}