In this problem, you need to check whether a graph can be colored with two colors so that any two adjacent vertices have different colors. Such a graph is called bipartite.
Let the first vertex have color ;
Then all its neighbors must have color ;
The neighbors of vertices with color must again have color ;
And so on…
That is, the colors of the vertices must alternate along the depth of the traversal.
To solve the problem, we use depth-first search. Initially, all vertices are considered unvisited and are assigned color . During the traversal, we color the vertices using two colors: and . If the current vertex has color (where i = 1 or ), then each next vertex we visit in the DFS is colored with 3 - i. At each step, we check that no two adjacent vertices are assigned the same color.
Example
The graphs shown in the example have the following form:
Algorithm implementation
Store the graph's adjacency matrix in an array of size MAX = 1001 (vertices are numbered from to n \le 1000). The array stores the color of each vertex. The global variable indicates whether the coloring is valid: as soon as two adjacent vertices with the same color are found, this variable is set to .
#define MAX 1000
int g[MAX][MAX], used[MAX], flag;The function dfs performs a depth-first search. It takes two parameters: the current vertex and its color .
void dfs(int v, int color = 1)
{If a case has already been detected where the required coloring is impossible (flag = 1), the function terminates.
if (flag) return;Assign color to vertex color.
used[v] = color;Examine all vertices that can be reached from vertex , continuing the depth-first traversal.
If vertex is not yet visited, start a DFS from it, passing the opposite color to the dfs function.
If vertex is already visited, check whether the coloring is valid: if vertices and have the same color, this violates the bipartite condition, set flag = 1.
for (int i = 1; i <= n; i++)
if (g[v][i] == 1)
if (used[i] == 0) dfs(i, 3 - color); else
if (used[v] == used[i]) flag = 1;
}The main part of the program. Read the number of vertices and the number of edges of the graph. Initialize the adjacency matrix and the array to zero.
while(scanf("%d %d",&n,&l), n)
{
memset(g,0,sizeof(g));
memset(used,0,sizeof(used));Read the edges of the graph.
for(i = 0; i < l; i++)
{
scanf("%d %d",&a,&b);
g[a][b] = g[b][a] = 1;
}Reset the variable to zero and start a depth-first search from the first vertex, assigning it color in advance.
flag = 0;
dfs(1);Depending on the value of the variable , print the result.
if (flag) printf("NOT BICOLOURABLE.\n");
else printf("BICOLOURABLE.\n");
}