TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
graph_coloring.cpp
Go to the documentation of this file.
1
21#include <array>
22#include <iostream>
23#include <vector>
24
29namespace backtracking {
35namespace graph_coloring {
41template <size_t V>
42void printSolution(const std::array<int, V>& color) {
43 std::cout << "Following are the assigned colors\n";
44 for (auto& col : color) {
45 std::cout << col;
46 }
47 std::cout << "\n";
48}
49
61template <size_t V>
62bool isSafe(int v, const std::array<std::array<int, V>, V>& graph,
63 const std::array<int, V>& color, int c) {
64 for (int i = 0; i < V; i++) {
65 if (graph[v][i] && c == color[i]) {
66 return false;
67 }
68 }
69 return true;
70}
71
81template <size_t V>
82void graphColoring(const std::array<std::array<int, V>, V>& graph, int m,
83 std::array<int, V> color, int v) {
84 // base case:
85 // If all vertices are assigned a color then return true
86 if (v == V) {
87 printSolution<V>(color);
88 return;
89 }
90
91 // Consider this vertex v and try different colors
92 for (int c = 1; c <= m; c++) {
93 // Check if assignment of color c to v is fine
94 if (isSafe<V>(v, graph, color, c)) {
95 color[v] = c;
96
97 // recur to assign colors to rest of the vertices
98 graphColoring<V>(graph, m, color, v + 1);
99
100 // If assigning color c doesn't lead to a solution then remove it
101 color[v] = 0;
102 }
103 }
104}
105} // namespace graph_coloring
106} // namespace backtracking
107
112int main() {
113 // Create following graph and test whether it is 3 colorable
114 // (3)---(2)
115 // | / |
116 // | / |
117 // | / |
118 // (0)---(1)
119
120 const int V = 4; // number of vertices in the graph
121 std::array<std::array<int, V>, V> graph = {
122 std::array<int, V>({0, 1, 1, 1}), std::array<int, V>({1, 0, 1, 0}),
123 std::array<int, V>({1, 1, 0, 1}), std::array<int, V>({1, 0, 1, 0})};
124
125 int m = 3; // Number of colors
126 std::array<int, V> color{};
127
128 backtracking::graph_coloring::graphColoring<V>(graph, m, color, 0);
129 return 0;
130}
void graphColoring(const std::array< std::array< int, V >, V > &graph, int m, std::array< int, V > color, int v)
Recursive utility function to solve m coloring problem.
void printSolution(const std::array< int, V > &color)
A utility function to print the solution.
bool isSafe(int v, const std::array< std::array< int, V >, V > &graph, const std::array< int, V > &color, int c)
Utility function to check if the current color assignment is safe for vertex v.
int main()
Main function.
for vector container
Functions for the Graph Coloring algorithm,.
Graph Algorithms.