Files
LeetCode-Go/leetcode/0785.Is-Graph-Bipartite/785. Is Graph Bipartite.go
2020-10-06 13:26:32 +08:00

36 lines
667 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package leetcode
// DFS 染色1 是红色0 是绿色,-1 是未染色
func isBipartite(graph [][]int) bool {
colors := make([]int, len(graph))
for i := range colors {
colors[i] = -1
}
for i := range graph {
if !dfs(i, graph, colors, -1) {
return false
}
}
return true
}
func dfs(n int, graph [][]int, colors []int, parentCol int) bool {
if colors[n] == -1 {
if parentCol == 1 {
colors[n] = 0
} else {
colors[n] = 1
}
} else if colors[n] == parentCol {
return false
} else if colors[n] != parentCol {
return true
}
for _, c := range graph[n] {
if !dfs(c, graph, colors, colors[n]) {
return false
}
}
return true
}