@@ -569,7 +569,41 @@ def color_graph(
569569 # Fall back to DSatur for large graphs
570570 coloring = dsatur_coloring (graph )
571571 else :
572- coloring = dsatur_coloring (graph )
572+ # Use backtracking to find an optimal coloring with chi colors
573+ adj = build_adjacency_list (graph )
574+ node_ids = [node .id for node in graph .nodes ]
575+ node_index = {node_id : i for i , node_id in enumerate (node_ids )}
576+ n = len (node_ids )
577+ colors = [- 1 ] * n
578+
579+ def is_safe (node_idx : int , color : int ) -> bool :
580+ """Check if assigning color to node is safe."""
581+ node_id = node_ids [node_idx ]
582+ for neighbor in adj .get (node_id , set ()):
583+ neighbor_idx = node_index [neighbor ]
584+ if colors [neighbor_idx ] == color :
585+ return False
586+ return True
587+
588+ def backtrack (node_idx : int ) -> bool :
589+ """Try to color nodes starting from node_idx."""
590+ if node_idx == n :
591+ return True
592+
593+ for color in range (chi ):
594+ if is_safe (node_idx , color ):
595+ colors [node_idx ] = color
596+ if backtrack (node_idx + 1 ):
597+ return True
598+ colors [node_idx ] = - 1
599+
600+ return False
601+
602+ if backtrack (0 ):
603+ coloring = {node_ids [i ]: colors [i ] for i in range (n )}
604+ else :
605+ # Should not happen if chi is correct, but fallback to DSatur
606+ coloring = dsatur_coloring (graph )
573607 else :
574608 raise ValueError (f"Unknown algorithm: { algorithm } " )
575609
0 commit comments