Skip to content

Commit e85635e

Browse files
785.Is Graph Bipartite?
Adding a new solution, Leetcode Q.785 solution in Go lang using Depth First Search, faster than 100 % ( 20ms ) with a memory usage of 12 MB.
1 parent e6a965f commit e85635e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

leetcode/785.Is Graph Bipartite?

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
func isBipartite(graph [][]int) bool {
2+
colors := make([]int,len(graph))
3+
4+
5+
for i := range colors {
6+
colors[i] = -1
7+
}
8+
9+
10+
for i := range graph {
11+
if !dfs(i, graph, colors, -1) {
12+
fmt.Println(colors)
13+
return false
14+
}
15+
}
16+
17+
fmt.Println(colors)
18+
return true
19+
20+
}
21+
22+
func dfs(n int, graph [][]int, colors []int, parentCol int) bool {
23+
if colors[n] == -1 {
24+
if parentCol == 1 {
25+
colors[n] = 0
26+
} else {
27+
colors[n] = 1
28+
}
29+
} else if colors[n] == parentCol {
30+
fmt.Println(n)
31+
return false
32+
} else if colors[n] != parentCol {
33+
return true
34+
}
35+
36+
37+
for _, c := range graph[n] {
38+
if !dfs(c, graph, colors, colors[n]) {
39+
fmt.Println(c)
40+
return false
41+
}
42+
}
43+
return true
44+
}

0 commit comments

Comments
 (0)