//here,we are just coloring the adjacent vertices with different color and if the any vertex is not visitied and it's color is equal to that of the current vertex we return false. vector g[100001]; vector visi(100001, 0); vector color(100001, 0); bool dfs(int v, int c) { visi[v] = true; color[v] = c; for (int child : g[v]) { if (visi[child] == false) { if (dfs(child, c ^ 1) == false) return false; } else { if (color[child] == color[v]) return false; } } return true; } //here,c^1 is a logical xor operation //this function return's true if graph is bipartite else false
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter