Skip to content

Instantly share code, notes, and snippets.

@fengyitsai
Created January 13, 2020 12:08
Show Gist options
  • Save fengyitsai/f13ee31ec7486be4b7fd2b39e189738d to your computer and use it in GitHub Desktop.
Save fengyitsai/f13ee31ec7486be4b7fd2b39e189738d to your computer and use it in GitHub Desktop.
785. Is Graph Bipartite?
class Solution {
func isBipartite(_ graph: [[Int]]) -> Bool {
var group = [Int:Bool]()
for (index, node) in graph.enumerated() {
guard group[index] == nil else {
continue
}
var queue = [index]
var currentGroup = true
while !queue.isEmpty {
var nextQueue = [Int]()
for node in queue {
if let nodeGroup = group[node] {
if nodeGroup != currentGroup {
return false
} else {
continue
}
} else {
group[node] = currentGroup
nextQueue.append(contentsOf: graph[node])
}
}
currentGroup.toggle()
queue = nextQueue
}
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment