-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColorGraphWithMColors.cpp
95 lines (80 loc) · 2.7 KB
/
ColorGraphWithMColors.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "CppUnitTest.h"
#include <string>
#include <memory>
#include <cassert>
#include <array>
namespace ColorGraphWithMColors {
const int BLANK = 0;
template <size_t size>
bool neighborsShareColor(const std::array<std::array<bool, size>, size>& graph, std::array<int, size> colors, int currentVertex, int color) {
for (int a = 0; a < graph.size(); a++) {
if (graph[currentVertex][a] && colors[a] == color)
return true;
}
return false;
}
template <size_t size>
bool colorGraph(const std::array<std::array<bool,size>,size>& graph, int numColors, std::array<int,size>& colors, int currentVertex) {
// Base Case: if all of the vertexes have been colored then we are done.
if (currentVertex == size) { return true; }
// Try out each color on this node
for (int c = 1; c <= numColors; c++) {
// if any neighboring nodes have same color try new color.
if (neighborsShareColor(graph, colors, currentVertex, c))
continue;
// Try out this color
colors[currentVertex] = c;
// If we are able to recursively color all following nodes.
if (colorGraph(graph, numColors, colors, currentVertex + 1))
return true;
// No workable combination of colors could be found with
// this node set c so backtrack and try a new color.
colors[currentVertex] = BLANK;
}
// No color could be found for this node that lead to a solution.
return false;
}
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
TEST_CLASS(ColorGraphWithMColorsTests) {
public:
TEST_METHOD(WhenLessThanMinAmountOfColorsNeeded_ExpectFalse) {
std::array<std::array<bool, 4>, 4> graph =
{ {
{ 0, 1, 0, 1 },
{ 1, 0, 1, 0 },
{ 0, 1, 0, 1 },
{ 1, 0, 1, 0 }
} };
std::array<int, 4> colors;
colors.fill(BLANK);
auto result = colorGraph(graph, 1, colors, 0);
Assert::IsFalse(result);
}
TEST_METHOD(WhenMinAmountOfColorsNeeded_ExpectTrue) {
std::array<std::array<bool, 4>, 4> graph =
{ {
{ 0, 1, 0, 1 },
{ 1, 0, 1, 0 },
{ 0, 1, 0, 1 },
{ 1, 0, 1, 0 }
} };
std::array<int, 4> colors;
colors.fill(BLANK);
auto result = colorGraph(graph, 2, colors, 0);
Assert::IsTrue(result);
}
TEST_METHOD(WhenMoreThanAmountOfColorsNeeded_ExpectTrue) {
std::array<std::array<bool, 4>, 4> graph =
{ {
{ 0, 1, 0, 1 },
{ 1, 0, 1, 0 },
{ 0, 1, 0, 1 },
{ 1, 0, 1, 0 }
} };
std::array<int, 4> colors;
colors.fill(BLANK);
auto result = colorGraph(graph, 10, colors, 0);
Assert::IsTrue(result);
}
};
}