# Python implementation and C implementation of the eight queens problem

I like the solution to the eight queens problem. The version I implemented with C is posted on Baidu Encyclopedia (https://baike.baidu.com/item/% E5% 85% AB% E7% 9A% 87% E5% 90% 8e% E9% 97% AE% E9% A2% 98 × 22 × 7). Baidu Encyclopedia has Python version, and the efficiency is a little higher than mine, so I decided to post my version in the blog park. I believe my version is easier to understand. I hope it can help you. Upper Code:

Python:

# EightQueens.py
def checkConflict(queenList, nextY):
for posY in range(nextY):
if abs(queenList[posY]-queenList[nextY])==abs(posY-nextY) or queenList[posY] == queenList[nextY]:
return True
return False

count = 0
def putQueen(queenCount, queenList, nextY):
for queenList[nextY] in range(queenCount):
if checkConflict(queenList, nextY)==False:
nextY+=1

if nextY < queenCount:
putQueen(queenCount, queenList, nextY)
else:
global count
count+=1
print(str(count)+": " + ", ".join(str(pos) for pos in queenList))

nextY-=1

# call the method
queenCount = 12
queenList = [0] * queenCount
putQueen(queenCount, queenList, 0)

C#:

// EightQueens.cs
namespace EightQueens
{
class EightQueens
{
private bool checkConflict(List<int> queenList, int nextY)
{
for (int positionY = 0; positionY < nextY; positionY++)
{
if (Math.Abs(queenList[positionY] - queenList[nextY]) == Math.Abs(positionY - nextY) || queenList[positionY] == queenList[nextY])
{
return true;
}
}
return false;
}

long count = 0;
public void putQueen(int queenCount, List<int> queenList, int nextY)
{
for (queenList[nextY] = 0; queenList[nextY] < queenCount; queenList[nextY]++)
{
if (checkConflict(queenList, nextY) == false)
{
nextY++;
if (nextY < queenCount)
{
putQueen(queenCount, queenList, nextY);
}
else
{
count++;
Console.WriteLine(count.ToString() + ": " + string.Join(", ", queenList));
}
nextY--;
}
}
}
}
}

Method call:

// Program.cs
namespace EightQueens
{
class Program
{
static void Main(string[] args)
{
int queenCount = 12;
List<int> queenList = new List<int>();
for (int i = 0; i < queenCount; i++)
{