From e85635e6f945cad53e27aa286cfd5185ee363172 Mon Sep 17 00:00:00 2001 From: Aman Dwivedi <57112545+born69confused@users.noreply.github.com> Date: Sun, 4 Oct 2020 15:38:27 +0530 Subject: [PATCH] 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. --- leetcode/785.Is Graph Bipartite? | 44 ++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 leetcode/785.Is Graph Bipartite? diff --git a/leetcode/785.Is Graph Bipartite? b/leetcode/785.Is Graph Bipartite? new file mode 100644 index 00000000..aadc2330 --- /dev/null +++ b/leetcode/785.Is Graph Bipartite? @@ -0,0 +1,44 @@ +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) { + fmt.Println(colors) + return false + } + } + + fmt.Println(colors) + 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 { + fmt.Println(n) + return false + } else if colors[n] != parentCol { + return true + } + + + for _, c := range graph[n] { + if !dfs(c, graph, colors, colors[n]) { + fmt.Println(c) + return false + } + } + return true +}