Created
January 13, 2020 12:08
-
-
Save fengyitsai/f13ee31ec7486be4b7fd2b39e189738d to your computer and use it in GitHub Desktop.
785. Is Graph Bipartite?
This file contains hidden or 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
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