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
20
21#include <array>
22#include <iostream>
23
28namespace backtracking {
34namespace graph_coloring {
40template <size_t V>
41void printSolution(const std::array<int, V>& color) {
42 std::cout << "Following are the assigned colors\n";
43 for (auto& col : color) {
44 std::cout << col;
45 }
46 std::cout << "\n";
47}
48
60template <size_t V>
61bool isSafe(int v, const std::array<std::array<int, V>, V>& graph,
62 const std::array<int, V>& color, int c) {
63 for (int i = 0; i < V; i++) {
64 if (graph[v][i] && c == color[i]) {
65 return false;
66 }
67 }
68 return true;
69}
70
80template <size_t V>
81void graphColoring(const std::array<std::array<int, V>, V>& graph, int m,
82 std::array<int, V> color, int v) {
83 // base case:
84 // If all vertices are assigned a color then return true
85 if (v == V) {
86 printSolution<V>(color);
87 return;
88 }
89
90 // Consider this vertex v and try different colors
91 for (int c = 1; c <= m; c++) {
92 // Check if assignment of color c to v is fine
93 if (isSafe<V>(v, graph, color, c)) {
94 color[v] = c;
95
96 // recur to assign colors to rest of the vertices
97 graphColoring<V>(graph, m, color, v + 1);
98
99 // If assigning color c doesn't lead to a solution then remove it
100 color[v] = 0;
101 }
102 }
103}
104} // namespace graph_coloring
105} // namespace backtracking
106
111int main() {
112 // Create following graph and test whether it is 3 colorable
113 // (3)---(2)
114 // | / |
115 // | / |
116 // | / |
117 // (0)---(1)
118
119 const int V = 4; // number of vertices in the graph
120 std::array<std::array<int, V>, V> graph = {
121 std::array<int, V>({0, 1, 1, 1}), std::array<int, V>({1, 0, 1, 0}),
122 std::array<int, V>({1, 1, 0, 1}), std::array<int, V>({1, 0, 1, 0})};
123
124 int m = 3; // Number of colors
125 std::array<int, V> color{};
126
128 return 0;
129}
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.