forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[DFS] Add a solution to Is Graph Bipartite
- Loading branch information
Showing
2 changed files
with
39 additions
and
1 deletion.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
} | ||
} |
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