Click here to Skip to main content
15,312,747 members
Articles / General Programming / Algorithms
Posted 27 Jul 2014


36 bookmarked

A Sudoku Solver using Graph Coloring

Rate me:
Please Sign up or sign in to vote.
4.89/5 (34 votes)
28 Jul 2014CPOL5 min read
This article explains the concept of graph coloring and how to use graph coloring to solve Sudoku Puzzles.



In this article, I will explain the concept of graph coloring and how it can be used to solve a 9x9 Sudoku Puzzle. This article assumes that the reader is already familiar with the concept of a graph and its representation.

Graph Coloring Demystified

A graph is a mathematical representation of a set of objects where some pairs of objects are connected (linked) to each other. The objects are represented by vertices (nodes) and the links are called edges.


A Graph with 5 nodes and 5 edges

A Graph with 5 nodes and 5 edges

Graph coloring is the assignment of "colors" to vertices of the graph such that no two adjacent vertices share the same color. For example, in the graph mentioned above vertices 1 and 2 cannot have the same color because they have an edge connecting them. However, vertices 2 and 3 can have the same color because they are not connected. Below is one possible coloring of this graph.

Image 2

It should be clear by now that one graph can have more than one possible coloring. The goal is to use the minimum number of colors possible. Below are another two possible colorings for the example graph. Coloring (1) uses the 3 colors while Coloring (2) uses 5 colors, hence, coloring (1) is better than coloring (2).

Image 3

Our color is to find a coloring of a given graph that uses the minimum number of colors. A coloring that uses at most k colors is called k-coloring (e.g. coloring (1) in the above example is a 3-coloring while coloring (2) is a 5-coloring).

If you tried to color the above graph using only two colors you will find out that it cannot be colored at all, Go try it out I will wait :). Therefore, the smallest number of colors needed to color a graph is called its chromatic number.

Contraction and Greedy Coloring Algorithms

Graph coloring is computationally hard and it has been a research topic for many years. Most of the algorithms can be broadly categorized in one of two main topics “Contraction” and “Greedy Coloring”.

Greedy Coloring focuses on carefully picking the next vertex to be colored. Once a vertex is colored, its color never changes. Algorithms under this category differ in the way the next vertex is selected.

A famous algorithm under this category is the Welsh–Powell algorithm. It works as follows:

1. Find the degree of each vertex. (Degree: is the number of edges connected to it)

2. Order the vertices in descending order according to their degree.

3. Go through the list, color each vertex not connected to colored vertices with the same color.

4. Remove colored vertices from the list and repeat the process until all vertices are colored.

Let’s go back to our example.

Image 4

Step 1:













Step 2: The order is 1,5,3,2,4

Step 3:

Vertex   Action



Color red



Don’t color red because it is connected to 1



Don’t color red because it is connected to 1



Don’t color red because it is connected to 1



Color red

Now the graph looks like this and the new list is  5,3,2

Image 5

Vertex   Action



Color blue



Don’t color blue because it is connected to 5



Color blue


Now the graph looks like this and we are left with one vertex which will be colored green.

Image 6

The second category “Contraction” works by finding two vertices removing any edges between them, and replacing them with a single vertex where any edges that were connected to any of them are now redirected to new single vertex. A contraction algorithm would work as follows:

1. Select the vertex of maximum degree V.

2. Find the set of non-adjacent vertices to V.

3. From this set select the vertex Y of maximum common vertices with V.

4. Contract Y into V to be colored with the same color.

5. Remove Y from the set and repeat steps 3-5 until the list is empty.

6 .Remove vertex V from the graph

7. Repeat steps 1-6 until the resulting graph has all contracted nodes adjacent to each other.

Let’s go back to our example. Vertex (1) has the maximum degree; its non adjacent vertices are vertex (4). Hence, Vertex (1) and (4) are contracted into one node.

Image 7


Now, the vertex with maximum degree is ({1,4}) and it all remaining vertices are adjacent. Hence, remove vertex ({1,4}) from the graph and select vertex with maximum degree.


Image 8


Now, vertex (3) has maximum degree and it has one non adjacent vertex (2). Vertex (3) and (2) are contracted into a single vertex.

Image 9

Vertex ({3,2}) has no non adjacent vertices, hence, it will be removed from the graph. We are left with a single vertex (5); our work is done. The algorithm produces three groups {1,4}, {2,3} and {5} each group will take a different color.

Image 10

Implemented Algorithm

In my implementation, I choose a greedy coloring algorithm with some modifications as proposed in the paper by Dr. Hussein Al-Omari and Khair Eddin Sabri published in the American Journal of Mathematics and Statistics.

As I discussed earlier, the trick is choosing the next vertex to color. The proposed algorithm uses a combination of saturated degree ordering (SDO) and degree ordering that we explained earlier.

The saturation degree of a vertex is the number of its adjacent differently colored vertices.  The vertices are ordered according to their saturation degree and if two vertices have the same degree the tie is broken by comparing their degree.

int colorNumber = 1; //number of used colors
int numberOfColoredNodes = 0;

while (numberOfColoredNodes < graph.Count)
 var max = -1;
 var index = -1;

 for (int i = 0; i < graph.Count; i++)
  if (!Colored(graph.Nodes[i], nodeSet))
   var d = SaturatedDegree(graph.Nodes[i], nodeSet);
   if (d > max)
    max = d;
    index = i;
   else if (d == max)
    if (Degree(graph.Nodes[i]) > Degree(graph.Nodes[index]))
     index = i;
 AssignColor(graph.Nodes[index], nodeSet,ref colorNumber);

Sudoku Solver

A Sudoku puzzle (9x9) can be thought of a graph with 81 vertices, one for each cell, and two vertices are connected by an edge if they cannot be assigned the same value. For example, all cells in the same row, column or block will have edges between their corresponding vertices.

Given a Sudoku puzzle we can build the associated graph. The given number in the puzzle cane be used to add additional edges to the graph we can then use graph coloring to find a 9-coloring of this graph (colors 1-9)Image 11

Points of Interest

The optimal solution in the case of the Sudoku puzzle is to find a coloring using only 9 colors. Some algorithms behave better than others and it is usually a tradeoff between runtime complexity and the number of colors used. Currently not all puzzles can be solved; for some puzzles the algorithm cannot find a coloring that uses only nine colors.  An example of a puzzle that cannot be solved is given below.

Image 12

I hope you liked this post if you have any questions please leave a comment.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mostafa Eissa
Software Developer (Junior)
Egypt Egypt
No Biography provided

Comments and Discussions

Question?? Pin
Member 1484432026-May-20 6:37
MemberMember 1484432026-May-20 6:37 
QuestionWhat is the complexity please? Pin
Member 131729514-May-17 8:28
MemberMember 131729514-May-17 8:28 
GeneralThank you Pin
PIEBALDconsult4-Apr-16 19:33
professionalPIEBALDconsult4-Apr-16 19:33 
QuestionWhat is the complexity Pin
Member 109475864-Apr-16 2:34
MemberMember 109475864-Apr-16 2:34 
GeneralMy vote of 5 Pin
Pratik Bhuva26-Aug-15 20:56
professionalPratik Bhuva26-Aug-15 20:56 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA13-Aug-14 3:12
professionalȘtefan-Mihai MOGA13-Aug-14 3:12 
GeneralMy vote of 5 Pin
losvce6-Aug-14 5:42
Memberlosvce6-Aug-14 5:42 
Suggestiontoo much "color" :-) Pin
sx20083-Aug-14 0:50
Membersx20083-Aug-14 0:50 
GeneralNice Article Pin
Suchi Banerjee, Pune28-Jul-14 3:01
MemberSuchi Banerjee, Pune28-Jul-14 3:01 
QuestionWelsh–Powell algorithm example: Is Degree of vertex 5 really 1 Pin
L. Braun28-Jul-14 1:23
MemberL. Braun28-Jul-14 1:23 
AnswerRe: Welsh–Powell algorithm example: Is Degree of vertex 5 really 1 Pin
Mostafa Eissa28-Jul-14 2:18
professionalMostafa Eissa28-Jul-14 2:18 
GeneralRe: Welsh–Powell algorithm example: Is Degree of vertex 5 really 1 Pin
Dharma Putra18-May-18 19:52
MemberDharma Putra18-May-18 19:52 
Questiona minior mistaken Pin
ray_linn27-Jul-14 20:03
Memberray_linn27-Jul-14 20:03 
AnswerRe: a minior mistaken Pin
Mostafa Eissa28-Jul-14 0:01
professionalMostafa Eissa28-Jul-14 0:01 
Yes, you are correct, It should be "connected to 3". I corrected it now. Thank you for pointing this out to me.
GeneralNice job! Pin
Ravi Bhavnani27-Jul-14 8:54
professionalRavi Bhavnani27-Jul-14 8:54 
GeneralMy vote of 5 Pin
newton.saber27-Jul-14 5:42
Membernewton.saber27-Jul-14 5:42 
GeneralRe: My vote of 5 Pin
Mostafa Eissa27-Jul-14 6:10
professionalMostafa Eissa27-Jul-14 6:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.