1. Brute Force All Color Combinations
Intuition
Iterate across all combinations from 11..1 to mm..m. For each full coloring, verify all E edges.
Algorithm
- Step 1: Assign each of the V vertices one of M colors from 1 to M.
- Step 2: When all V vertices have a color assigned (node == V), validate every edge (u, v).
- Step 3: If any edge connects two vertices of identical color, return false.
- Step 4: If all edges connect vertices of distinct colors, return true.
#include <iostream>#include <vector> class Solution {public: bool isValid(int v, const std::vector<std::vector<int>>& graph, const std::vector<int>& color) { for (int i = 0; i < v; i++) { for (int j = i + 1; j < v; j++) { if (graph[i][j] && color[i] == color[j]) return false; } } return true; } bool generateAll(int node, int v, int m, const std::vector<std::vector<int>>& graph, std::vector<int>& color) { if (node == v) return isValid(v, graph, color); for (int c = 1; c <= m; c++) { color[node] = c; if (generateAll(node + 1, v, m, graph, color)) return true; } return false; } bool graphColoring(int v, std::vector<std::pair<int, int>>& edges, int m) { std::vector<std::vector<int>> graph(v, std::vector<int>(v, 0)); for (auto& e : edges) { graph[e.first][e.second] = 1; graph[e.second][e.first] = 1; } std::vector<int> color(v, 0); return generateAll(0, v, m, graph, color); }}; int main() { Solution solver; std::vector<std::pair<int, int>> edges = {{0,1},{1,2},{2,3},{3,0},{0,2}}; std::cout << "Can color graph with 3 colors: " << (solver.graphColoring(4, edges, 3) ? "true" : "false") << "\n"; return 0;}Time & Space Complexity
- Time complexity:
O(M^V * (V + E))— Generates MV combinations and checks all E edges for each. - Space complexity:
O(V)— O(V) for color assignment array.