# How to Solve Constraint Satisfaction Problems (CSPs) Using **AC-3 Algorithm in Python**

## AI Optimization Algorithm

The AC-3 algorithm simplifies a constraint satisfaction problem using the constraints to prune out values from the variables domain.

In this article, we will see how the AC-3 algorithm works and the implementation in Python.

# How It Works

We can represent the AC-3 algorithm in 3 steps:

- Get all the constraints and turn each one into two arcs. For example:

π΄ > π΅ becomes π΄ > π΅ and π΅ < π΄. - Add all the arcs to a queue.
- Repeat until the queue is empty:

3.1. Take the first arc (**π₯**,**π¦**), off the queue (**dequeue**).

3.2. For**every**value in the**π₯**domain, there must be some value of the**π¦**domain.

3.3. Make**π₯**arc consistent with**π¦**. To do so, remove values from**π₯**domain for which there is no possible corresponding value for**π¦**domain.

3.4. If the**π₯**domain has changed, add all arcs of the form (**π**,**π₯**) to the queue (**enqueue**). Here**π**is another variable different from**π¦**that has a relation to**π₯**.

# Example

Letβs take this example, where we have three variables π΄, π΅, and πΆ and the constraints: π΄ > π΅ and π΅ = πΆ.

## Step 1: Generate All Arcs

The first thing to do is to work out all our arcs. We take the constraint π΄ > π΅ and generate π΄ > π΅ and π΅οΉ€π΄. With the constraint π΅ = πΆ we will have π΅ = πΆ and πΆ = π΅.

## Step 2: Create the Queue

We now take all generated arcs and add them to our queue.

## Step 3: Iterate Over the Queue

First, we will take the first item in the queue (π΄ > π΅) and remove it, and we are going through all the values of the π΄ domain. For each value of π΄, we will compare it with the values of π΅. If there are no values in π΅ for the value of π΄, we remove this value from π΄. As the domain of π΄ has changed, we have to look at the right side of all the arcs. Whether there are variables for π΄ and that arc is not already in the queue. As we can see, this is not the case here.

On the second iteration, we take the first item in the queue (π΅οΉ€π΄). After removing all the inconsistent values in the π΅ domain, we notice that it has been modified. Looking at all the arcs and checking whether there is the variable π΅ on the right side, we can see that the arc π΄ > π΅ is not in the queue, so we have to add it again to the queue.

Now, we will keep doing that until the queue is empty. In the end, we will have the following state:

# Solution in Python

Here is the implementation of the AC-3 algorithm (with the previous example) in Python.

# Conclusion

The time complexity of AC-3 is π(ππΉΒ³), where π is the number of constraints and πΉ is the size of the maximum domain in a problem.

AC-3 is an algorithm with non-optimal worst-case complexity although, it is simple, efficient in practice, and widely used.