Skip to content

Graph Coloring Problem in Greedy Algorithms #10213

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
48 changes: 48 additions & 0 deletions greedy_methods/graph_coloring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import doctest


def graph_coloring(graph: list[list[int]]) -> list[int]:
"""
Graph coloring algorithm using a greedy approach.

Parameters:
- graph (List[List[int]])

Returns:
- list[int]

Example:
>>> graph_coloring([[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]])
[0, 1, 2, 1]

>>> graph_coloring([[1], [0, 2], [1]])
[0, 1, 0]
"""

num_vertices = len(graph)
result = [-1] * num_vertices
result[0] = 0
available_colors = [True] * num_vertices

for u in range(1, num_vertices):
for i in graph[u]:
if result[i] != -1:
available_colors[result[i]] = False

cr = 0
while cr < num_vertices:
if available_colors[cr]:
break
cr += 1

result[u] = cr

for i in graph[u]:
if result[i] != -1:
available_colors[result[i]] = True

return result


if __name__ == "__main__":
doctest.testmod()
2 changes: 1 addition & 1 deletion scripts/validate_filenames.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/env python
import os

try:
Expand Down