using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NQueen.Console
{
class Program
{
// Toplam çözüm sayısını bu değişkende tutacağız
private static int SolutionCount = 0;
// Tahtamızın boyutunu buradan belirliyoruz
private static int BoardSize = 8;
// Satranç tahtamızı iki boyutlu bir dizi olarak belirliyoruz
private static int[,] ChessBoard;
static void Main(string[] args)
{
// Çözümleri bul!!!
FindSolutions();
}
/// <summary>
/// Çözümü bulan ana metodumuz
/// </summary>
static void FindSolutions()
{
SolutionCount = 0;
ChessBoard = new int[BoardSize + 1, BoardSize + 1];
Place(0, 0);
}
/// <summary>
/// col Paramatresi ile belirtilen sütunu temizler (tamamını sıfırlar)
/// </summary>
/// <param name="col">Sütun</param>
static void Initialize(int col)
{
for (int i = 0; i < BoardSize; i++)
{
for (int j = col; j < BoardSize; j++)
{
ChessBoard[i, j] = 0;
}
}
}
/// <summary>
/// Ekran üzerinde çözümü görmemizi sağlar
/// </summary>
static void Display()
{
int i, j, s;
// Yeni bir çözüm bulundu! Toplam çözüm sayısını arttır
SolutionCount += 1;
s = SolutionCount;
for (i = 0; i < BoardSize; i++)
{
for (j = 0; j < BoardSize; j++)
{
// Mevcut hücre içeriğini ekrana yazdır (0 ya da 1)
System.Console.Write(ChessBoard[i, j].ToString() + " ");
}
System.Console.WriteLine();
}
System.Console.WriteLine();
System.Console.WriteLine("Diğer çözümü görmek için enter'a basınız!");
System.Console.ReadLine();
}
/// <summary>
/// row ve col parametreleri ile belirtilen hücreye yeni bir vezirin yerleşip yerleşemeyeceğini test et
/// </summary>
/// <param name="row">Satır</param>
/// <param name="col">Sütun</param>
/// <returns>True ya da False</returns>
static bool Can_Place(int row, int col)
{
int i, j;
bool NoConflict;
NoConflict = true;
// satırı kontrol et
for (j = 0; j < col; j++)
{
if (ChessBoard[row, j] == 1)
NoConflict = false;
}
i = row - 1;
j = col - 1;
while ((i >= 0) && (j >= 0) && (NoConflict)) //Sol üst çapraz
{
if (ChessBoard[i, j] == 1)
NoConflict = false;
i = i - 1;
j = j - 1;
}
i = row + 1;
j = col - 1;
while ((i < BoardSize) && (j >= 0) && (NoConflict)) //Sağ alt çapraz
{
if (ChessBoard[i, j] == 1)
NoConflict = false;
i = i + 1;
j = j - 1;
}
return NoConflict;
}
/// <summary>
/// row ve col ile koordinatları verilen yere yeni bir vezir yerleştirir ve
/// eğer son satıra bir vezir yerleştirilmişse çözüm bulunmuştur, bulunan çözümü gösterir
/// </summary>
/// <param name="row">Satır</param>
/// <param name="col">Sütun</param>
static void Place(int row, int col)
{
if (col == BoardSize)
Display();
else
{
do
{
Initialize(col);
if (Can_Place(row, col))
{
ChessBoard[row, col] = 1;
Place(0, col + 1);
}
row++;
} while ((row < BoardSize));
}
}
}
}