数据结构和算法

DSA - 主页 DSA - 概述 DSA - 环境设置 DSA - 算法基础 DSA - 渐近分析

数据结构

DSA - 数据结构基础 DSA - 数据结构和类型 DSA - 数组数据结构

链接列表

DSA - 链接列表数据结构 DSA - 双向链接列表数据结构 DSA - 循环链表数据结构

堆栈 &队列

DSA - 堆栈数据结构 DSA - 表达式解析 DSA - 队列数据结构

搜索算法

DSA - 搜索算法 DSA - 线性搜索算法 DSA - 二分搜索算法 DSA - 插值搜索 DSA - 跳跃搜索算法 DSA - 指数搜索 DSA - 斐波那契搜索 DSA - 子列表搜索 DSA - 哈希表

排序算法

DSA - 排序算法 DSA - 冒泡排序算法 DSA - 插入排序算法 DSA - 选择排序算法 DSA - 归并排序算法 DSA - 希尔排序算法 DSA - 堆排序 DSA - 桶排序算法 DSA - 计数排序算法 DSA - 基数排序算法 DSA - 快速排序算法

图形数据结构

DSA - 图形数据结构 DSA - 深度优先遍历 DSA - 广度优先遍历 DSA - 生成树

树数据结构

DSA - 树数据结构 DSA - 树遍历 DSA - 二叉搜索树 DSA - AVL 树 DSA - 红黑树 DSA - B树 DSA - B+ 树 DSA - 伸展树 DSA - 尝试 DSA - 堆数据结构

递归

DSA - 递归算法 DSA - 使用递归的汉诺塔 DSA - 使用递归的斐波那契数列

分而治之

DSA - 分而治之 DSA - 最大最小问题 DSA - 施特拉森矩阵乘法 DSA - Karatsuba 算法

贪婪算法

DSA - 贪婪算法 DSA - 旅行商问题(贪婪方法) DSA - Prim 最小生成树 DSA - Kruskal 最小生成树 DSA - Dijkstra 最短路径算法 DSA - 地图着色算法 DSA - 分数背包问题 DSA - 作业排序截止日期 DSA - 最佳合并模式算法

动态规划

DSA - 动态规划 DSA - 矩阵链乘法 DSA - Floyd Warshall 算法 DSA - 0-1 背包问题 DSA - 最长公共子序列算法 DSA - 旅行商问题(动态方法)

近似算法

DSA - 近似算法 DSA - 顶点覆盖算法 DSA - 集合覆盖问题 DSA - 旅行商问题(近似方法)

随机算法

DSA - 随机算法 DSA - 随机快速排序算法 DSA - Karger 最小割算法 DSA - Fisher-Yates 洗牌算法

DSA 有用资源

DSA - 问答 DSA - 快速指南 DSA - 有用资源 DSA - 讨论


M-Coloring Problem

What is M-Coloring Problem?

In the M-Coloring problem, our task is to find if it is possible to assign nodes of a given graph with m different colors, such that no two adjacent vertices of the graph are of the same colors. If a solution exists, then display which color is assigned to each vertex. The m-coloring problem is practically used to solve problems like clustering, scheduling, job allocation problems and many more.

A graph is an abstract data type (ADT) consisting of a set of objects that are connected via links.

Input Output Scenario

Suppose the given undirected graph G(V, E) and its adjacency matrix are as follows −

M-Coloring

Let the maximum color m = 3, which indicates the maximum number of colors that can be used. The backtracking algorithm can be used to solve the m-coloring problem for the above graph. This algorithm will return which node will be assigned with which color. If the solution is not possible, it will return false.

For this case, the output should be Node 0 -> color 1, Node 1 -> color 2, Node 2 -> color 3, Node 3 -> color 2. The figure below illustrates the same −

M-Coloring output

Solving M-Coloring Problem using Backtracking Approach

The naive way to solve m-coloring problem is by generating all possible combinations of vertices with colors and checking if any combination satisfies the given constraints. However, this approach is inefficient for larger graphs.

To solve m-coloring problem using the backtracking approach, follow the below steps −

  • Starting from vertex 0, we will try to assign colors one by one to different nodes.

  • However, before assigning, we have to check whether the color is safe or not. Color is not safe when adjacent vertices contain the same color.

  • Next, we will check if is there any color assignment that satisfies the constraint. If it does, we mark that assignment as a solution to the m-coloring problem.

Example

In the following example, we will illustrate how to solve the m-coloring problem in a given undirected graph.

#include <stdio.h>
#include <stdlib.h> 
#include <stdbool.h>
#define V 4
bool graph[V][V] = {
   {0, 1, 1, 1},
   {1, 0, 1, 0},
   {1, 1, 0, 1},
   {1, 0, 1, 0}
};
void showColors(int color[]) {
   printf("Assigned Colors are:
");
   for (int i = 0; i < V; i++)
      printf("%d ", color[i]);
   printf("
");
}
//check whether putting a color valid for v
bool isValid(int v, int color[], int c) {
   for (int i = 0; i < V; i++)
      if (graph[v][i] && c == color[i])
         return false;
   return true;
}
bool graphColoring(int colors, int color[], int vertex) {
   //when all vertices are considered      
   if (vertex == V)
      return true;
   for (int col = 1; col <= colors; col++) {
      //check whether color is valid or not 
      if (isValid(vertex, color, col)) {
         color[vertex] = col;
         // go for additional vertices
         if (graphColoring(colors, color, vertex + 1))
            return true;
         color[vertex] = 0;
      }
   }
   //when no colors can be assigned
   return false;
}
bool checkSolution(int m) {
   //make color matrix for each vertex   
   int *color = (int *)malloc(V * sizeof(int)); 
   for (int i = 0; i < V; i++)
      //initially set to 0
      color[i] = 0;
   //for vertex 0 check graph coloring      
   if (graphColoring(m, color, 0) == false) {
      printf("Solution does not exist.
");
      free(color); 
      return false;
   }
   showColors(color);
   free(color); 
   return true;
}

int main() {
   // Number of colors    
   int colors = 3;
   checkSolution(colors);
   return 0;
}
#include<iostream>
#define V 4
using namespace std;
bool graph[V][V] = {
   {0, 1, 1, 1},
   {1, 0, 1, 0},
   {1, 1, 0, 1},
   {1, 0, 1, 0},
};
void showColors(int color[]) {
   cout << "Assigned Colors are: " <<endl;
   for (int i = 0; i < V; i++)
      cout << color[i] << " ";
   cout << endl;
}
//check whether putting a color valid for v
bool isValid(int v,int color[], int c) {    
   for (int i = 0; i < V; i++)
      if (graph[v][i] && c == color[i])
         return false;
   return true;
}
bool graphColoring(int colors, int color[], int vertex) {
   //when all vertices are considered    
   if (vertex == V)    
      return true;
   for (int col = 1; col <= colors; col++) {
      //check whether color is valid or not 
      if (isValid(vertex,color, col)) {     
         color[vertex] = col;
         // go for additional vertices
         if (graphColoring (colors, color, vertex+1) == true)    
            return true;
                   
         color[vertex] = 0;
      }
   }
   //when no colors can be assigned
   return false; 
}
bool checkSolution(int m) {
   //make color matrix for each vertex    
   int *color = new int[V];    
   for (int i = 0; i < V; i++)
      //initially set to 0
      color[i] = 0;      
   //for vertex 0 check graph coloring
   if (graphColoring(m, color, 0) == false) {    
      cout << "Solution does not exist.";
      return false;
   }
   showColors(color);
   return true;
}
int main() {
   // Number of colors    
   int colors = 3;      
   checkSolution (colors);
}
public class GraphColoring {
   static final int V = 4;
   static boolean[][] graph = {
      {false, true, true, true},
      {true, false, true, false},
      {true, true, false, true},
      {true, false, true, false}
   };
   static void showColors(int[] color) {
      System.out.println("Assigned Colors are:");
      for (int i = 0; i < V; i++) {
         System.out.print(color[i] + " ");
      }
      System.out.println();
   }
   //check whether putting a color valid for v
   static boolean isValid(int v, int[] color, int c) {
      for (int i = 0; i < V; i++) {
         if (graph[v][i] && c == color[i]) {
            return false;
         }
      }
      return true;
   }
   static boolean graphColoring(int colors, int[] color, int vertex) {
      //when all vertices are considered    
      if (vertex == V) {
         return true;
      }
      for (int col = 1; col <= colors; col++) {
         //check whether color is valid or not 
         if (isValid(vertex, color, col)) {
            color[vertex] = col;
            // go for additional vertices
            if (graphColoring(colors, color, vertex + 1)) {
               return true;
            }
            color[vertex] = 0;
         }
      }
      //when no colors can be assigned
        return false;
   }
   static boolean checkSolution(int m) {
      //make color matrix for each vertex 
      int[] color = new int[V];
      for (int i = 0; i < V; i++) {
         //initially set to 0
         color[i] = 0;
      }
      //for vertex 0 check graph coloring
      if (!graphColoring(m, color, 0)) {
         System.out.println("Solution does not exist.");
         return false;
      }
      showColors(color);
      return true;
   }
   public static void main(String[] args) {
      // Number of colors 
      int colors = 3;
      checkSolution(colors);
   }
}
V = 4
graph = [
    [0, 1, 1, 1],
    [1, 0, 1, 0],
    [1, 1, 0, 1],
    [1, 0, 1, 0]
]
def show_colors(color):
    print("Assigned Colors are:")
    for i in range(V):
        print(color[i], end=" ")
    print()

def is_valid(v, color, c):
    for i in range(V):
        if graph[v][i] and c == color[i]:
            return False
    return True

def graph_coloring(colors, color, vertex):
    if vertex == V:
        return True
    for col in range(1, colors + 1):
        if is_valid(vertex, color, col):
            color[vertex] = col
            if graph_coloring(colors, color, vertex + 1):
                return True
            color[vertex] = 0
    return False

def check_solution(m):
    color = [0] * V
    if not graph_coloring(m, color, 0):
        print("Solution does not exist.")
        return False
    show_colors(color)
    return True

if __name__ == "__main__":
    colors = 3
    check_solution(colors)

Output

Assigned Colors are: 
1 2 3 2