Skip to content

Commit 85510b7

Browse files
committed
fix: implemented detailed bactracking
1 parent bad0551 commit 85510b7

2 files changed

Lines changed: 35 additions & 5 deletions

File tree

evaluation_function/algorithms/coloring.py

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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

evaluation_function/algorithms/utils.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,6 @@
2121
# UNION-FIND DATA STRUCTURE
2222
# =============================================================================
2323

24-
class UnionFind:
25-
# UNION-FIND DATA STRUCTURE
26-
# =============================================================================
27-
2824
class UnionFind:
2925
"""
3026
Union-Find (Disjoint Set Union) data structure with path compression

0 commit comments

Comments
 (0)