{"id":26267,"date":"2017-10-26T20:45:17","date_gmt":"2017-10-26T15:15:17","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26267"},"modified":"2017-10-26T20:45:17","modified_gmt":"2017-10-26T15:15:17","slug":"java-algorithm-check-whether-given-graph-bipartite-not","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-check-whether-given-graph-bipartite-not\/","title":{"rendered":"Java Algorithm &#8211; Check whether a given graph is Bipartite or not"},"content":{"rendered":"<p>A Bipartite Graph is a graph whose vertices can be divided into two independent sets, U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from V to U. <span id=\"more-117119\"><\/span>In other words, for every edge (u, v), either u belongs to U and v to V, or u belongs to V and v to U. We can also say that there is no edge that connects vertices of same set.<\/p>\n<p>A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with even cycle using two colors. For example, see the following graph.<\/p>\n<p>It is not possible to color a cycle graph with odd cycle using two colors.<\/p>\n<p><strong><em>Algorithm to check if a graph is Bipartite:<\/em><\/strong><br \/>\nOne approach is to check whether the graph is 2-colorable or not using backtracking algorithm m coloring problem.<br \/>\nFollowing is a simple algorithm to find out whether a given graph is Birpartite or not using Breadth First Search (BFS).<br \/>\n1. Assign RED color to the source vertex (putting into set U).<br \/>\n2. Color all the neighbors with BLUE color (putting into set V).<br \/>\n3. Color all neighbor\u2019s neighbor with RED color (putting into set U).<br \/>\n4. This way, assign color to all vertices such that it satisfies all the constraints of m way coloring problem where m = 2.<br \/>\n5. While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices (or graph is not Bipartite)<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to find out whether a given graph is Bipartite or not<br\/>import java.util.*;<br\/>import java.lang.*;<br\/>import java.io.*;<br\/> <br\/>class Bipartite<br\/>{<br\/>    final static int V = 4; \/\/ No. of Vertices<br\/> <br\/>    \/\/ This function returns true if graph G[V][V] is Bipartite, else false<br\/>    boolean isBipartite(int G[][],int src)<br\/>    {<br\/>        \/\/ Create a color array to store colors assigned to all veritces.<br\/>        \/\/ Vertex number is used as index in this array. The value &#039;-1&#039;<br\/>        \/\/ of  colorArr[i] is used to indicate that no color is assigned<br\/>        \/\/ to vertex &#039;i&#039;.  The value 1 is used to indicate first color<br\/>        \/\/ is assigned and value 0 indicates second color is assigned.<br\/>        int colorArr[] = new int[V];<br\/>        for (int i=0; i&lt;V; ++i)<br\/>            colorArr[i] = -1;<br\/> <br\/>        \/\/ Assign first color to source<br\/>        colorArr[src] = 1;<br\/> <br\/>        \/\/ Create a queue (FIFO) of vertex numbers and enqueue<br\/>        \/\/ source vertex for BFS traversal<br\/>        LinkedList&lt;Integer&gt;q = new LinkedList&lt;Integer&gt;();<br\/>        q.add(src);<br\/> <br\/>        \/\/ Run while there are vertices in queue (Similar to BFS)<br\/>        while (q.size() != 0)<br\/>        {<br\/> <br\/>            \/\/ Dequeue a vertex from queue<br\/>            int u = q.poll();<br\/> <br\/>            \/\/ Find all non-colored adjacent vertices<br\/>            for (int v=0; v&lt;V; ++v)<br\/>            {<br\/>                \/\/ An edge from u to v exists and destination v is<br\/>                \/\/ not colored<br\/>                if (G[u][v]==1 &amp;&amp; colorArr[v]==-1)<br\/>                {<br\/>                    \/\/ Assign alternate color to this adjacent v of u<br\/>                    colorArr[v] = 1-colorArr[u];<br\/>                    q.add(v);<br\/>                }<br\/> <br\/>                \/\/ An edge from u to v exists and destination v is<br\/>                \/\/ colored with same color as u<br\/>                else if (G[u][v]==1 &amp;&amp; colorArr[v]==colorArr[u])<br\/>                    return false;<br\/>            }<br\/>        }<br\/>        \/\/ If we reach here, then all adjacent vertices can<br\/>        \/\/  be colored with alternate color<br\/>        return true;<br\/>    }<br\/> <br\/>    \/\/ Driver program to test above function<br\/>    public static void main (String[] args)<br\/>    {<br\/>        int G[][] = {{0, 1, 0, 1},<br\/>            {1, 0, 1, 0},<br\/>            {0, 1, 0, 1},<br\/>            {1, 0, 1, 0}<br\/>        };<br\/>        Bipartite b = new Bipartite();<br\/>        if (b.isBipartite(G, 0))<br\/>           System.out.println(&quot;Yes&quot;);<br\/>        else<br\/>           System.out.println(&quot;No&quot;);<br\/>    }<br\/>}<br\/> <br\/>\/\/ Contributed by Aakash Hasija<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Yes<\/pre>\n<p>The above algorithm works only if the graph is strongly connected. In above code, we always start with source 0 and assume that vertices are visited from it. One important observation is a graph with no edges is also Bipiartite. Note that the Bipartite condition says all edges should be from one set to another.<\/p>\n<p>We can extend the above code to handle cases when a graph is not connected. The idea is repeatedly call above method for all not yet visited vertices.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>C++ Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ C++ program to find out whether a given graph is Bipartite or not.<br\/>\/\/ It works for disconnected graph also.<br\/>#include &lt;bits\/stdc++.h&gt;<br\/>using namespace std;<br\/> <br\/>const int V = 4;<br\/> <br\/>\/\/ This function returns true if graph G[V][V] is Bipartite,<br\/>\/\/ else false<br\/>bool isBipartiteUtil(int G[][V], int src, int colorArr[])<br\/>{<br\/>    colorArr[src] = 1;<br\/> <br\/>    \/\/ Create a queue (FIFO) of vertex numbers and enqueue<br\/>    \/\/ source vertex for BFS traversal<br\/>    queue &lt;int&gt; q;<br\/>    q.push(src);<br\/> <br\/>    \/\/ Run while there are vertices in queue (Similar to BFS)<br\/>    while (!q.empty())<br\/>    {<br\/>        \/\/ Dequeue a vertex from queue ( Refer http:\/\/goo.gl\/35oz8 )<br\/>        int u = q.front();<br\/>        q.pop();<br\/> <br\/>         \/\/ Find all non-colored adjacent vertices<br\/>        for (int v = 0; v &lt; V; ++v)<br\/>        {<br\/>            \/\/ An edge from u to v exists and<br\/>            \/\/ destination v is not colored<br\/>            if (G[u][v] &amp;&amp; colorArr[v] == -1)<br\/>            {<br\/>                \/\/ Assign alternate color to this<br\/>                \/\/ adjacent v of u<br\/>                colorArr[v] = 1 - colorArr[u];<br\/>                q.push(v);<br\/>            }<br\/> <br\/>            \/\/ An edge from u to v exists and destination<br\/>            \/\/ v is colored with same color as u<br\/>            else if (G[u][v] &amp;&amp; colorArr[v] == colorArr[u])<br\/>                return false;<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ If we reach here, then all adjacent vertices can<br\/>    \/\/ be colored with alternate color<br\/>    return true;<br\/>}<br\/> <br\/>\/\/ Returns true if G[][] is Bipartite, else false<br\/>bool isBipartite(int G[][V])<br\/>{<br\/>    \/\/ Create a color array to store colors assigned to all<br\/>    \/\/ veritces. Vertex\/ number is used as index in this<br\/>    \/\/ array. The value &#039;-1&#039; of  colorArr[i] is used to<br\/>    \/\/ ndicate that no color is assigned to vertex &#039;i&#039;.<br\/>    \/\/ The value 1 is used to indicate first color is<br\/>    \/\/ assigned and value 0 indicates second color is<br\/>    \/\/ assigned.<br\/>    int colorArr[V];<br\/>    for (int i = 0; i &lt; V; ++i)<br\/>        colorArr[i] = -1;<br\/> <br\/>    \/\/ This code is to handle disconnected graoh<br\/>    for (int i = 0; i &lt; V; i++)<br\/>      if (colorArr[i] == -1)<br\/>        if (isBipartiteUtil(G, i, colorArr) == false)<br\/>           return false;<br\/> <br\/>     return true;<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main()<br\/>{<br\/>    int G[][V] = {{0, 1, 0, 1},<br\/>        {1, 0, 1, 0},<br\/>        {0, 1, 0, 1},<br\/>        {1, 0, 1, 0}<br\/>    };<br\/> <br\/>    isBipartite(G) ? cout &lt;&lt; &quot;Yes&quot; : cout &lt;&lt; &quot;No&quot;;<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Yes<\/pre>\n<p>Time Complexity of the above approach is same as that Breadth First Search. In above implementation is O(V^2) where V is number of vertices. If graph is represented using adjacency list, then the complexity becomes O(V+E).<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Check whether a given graph is Bipartite or not &#8211; Graph Algorithm &#8211; A Bipartite Graph is a graph whose vertices can be divided<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,74168,73906,2139],"tags":[78028,78022,78026,78029,78023,78021,78030,78065,78024,78031,78025,78027,78032],"class_list":["post-26267","post","type-post","status-publish","format-standard","hentry","category-coding","category-dfs-and-bfs","category-graph-algorithms","category-java","tag-bipartite-graph-algorithm","tag-bipartite-graph-algorithm-using-dfs","tag-bipartite-graph-applications","tag-bipartite-graph-c","tag-bipartite-graph-code-in-c","tag-bipartite-graph-example","tag-bipartite-graph-example-ppt","tag-bipartite-graph-geeksforgeeks","tag-bipartite-graph-matching","tag-bipartite-graph-pdf","tag-check-if-a-graph-is-bipartite-using-bfs","tag-complete-bipartite-graph","tag-tripartite-graph"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26267","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26267"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26267\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26267"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26267"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26267"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}