Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions backtracking/m_coloring_problem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
def is_safe(node: int, color: int, graph: list[list[int]], num_vertices: int, col: list[int]) -> bool:

Check failure on line 1 in backtracking/m_coloring_problem.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

backtracking/m_coloring_problem.py:1:89: E501 Line too long (102 > 88)
"""
Check if it is safe to assign a color to a node.

>>> is_safe(0, 1, [[0,1],[1,0]], 2, [0,1])
False
>>> is_safe(0, 2, [[0,1],[1,0]], 2, [0,1])
True
"""
return all(not (graph[node][k] == 1 and col[k] == color) for k in range(num_vertices))

Check failure on line 10 in backtracking/m_coloring_problem.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

backtracking/m_coloring_problem.py:10:89: E501 Line too long (90 > 88)


def solve(node: int, col: list[int], max_colors: int, num_vertices: int, graph: list[list[int]]) -> bool:

Check failure on line 13 in backtracking/m_coloring_problem.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

backtracking/m_coloring_problem.py:13:89: E501 Line too long (105 > 88)
"""
Recursively try to color the graph using at most max_colors.

>>> solve(0, [0]*3, 3, 3, [[0,1,0],[1,0,1],[0,1,0]])
True
>>> solve(0, [0]*3, 2, 3, [[0,1,0],[1,0,1],[0,1,0]])
False
"""
if node == num_vertices:
return True
for c in range(1, max_colors + 1):
if is_safe(node, c, graph, num_vertices, col):
col[node] = c
if solve(node + 1, col, max_colors, num_vertices, graph):
return True
col[node] = 0
return False


def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -> bool:
"""
Determine if the graph can be colored with at most max_colors.

>>> graph_coloring([[0,1,1],[1,0,1],[1,1,0]], 3, 3)
True
>>> graph_coloring([[0,1,1],[1,0,1],[1,1,0]], 2, 3)
False
"""
col = [0] * num_vertices
return solve(0, col, max_colors, num_vertices, graph)


if __name__ == "__main__":
num_vertices = int(input())
num_edges = int(input())
graph = [[0] * num_vertices for _ in range(num_vertices)]
for _ in range(num_edges):
u, v = map(int, input().split())
if 0 <= u < num_vertices and 0 <= v < num_vertices:
graph[u][v] = 1
graph[v][u] = 1
else:
raise ValueError("Edge indices out of range")
max_colors = int(input())
print(graph_coloring(graph, max_colors, num_vertices))
Loading