Skip to content

Instantly share code, notes, and snippets.

@masters3d
Created July 6, 2018 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masters3d/b80dc2a21fa1a860c4daa73bd18f37ec to your computer and use it in GitHub Desktop.
Save masters3d/b80dc2a21fa1a860c4daa73bd18f37ec to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace n_queen
{
class Program
{
static int gridSize = 4;
static int[] queens = Enumerable.Repeat(-1, gridSize).ToArray();
static bool validPosition(int row, int col) {
// We do not have to check Horizontal because
// we are only placing one queen per row
// Check Vertical
foreach(var each in queens)
{
if (each == col)
{
return false;
}
}
// Check Diagonal
var upRight = foundQueenOnPath(row , col, -1, 1);
var upLeft = foundQueenOnPath(row , col, -1, -1);
var downRight = foundQueenOnPath(row , col, 1, 1);
var downLeft = foundQueenOnPath(row , col, 1, -1);
var foundQueen = upRight || upLeft || downRight || downLeft;
return !foundQueen;
}
static bool foundQueenOnPath(int row, int col, int rowIncrement, int colIncrement)
{
if (col < 0 || col >= gridSize)
{
return false;
}
if (row < 0 || row >= gridSize)
{
return false;
}
var value = queens[row];
if(value == col)
{
return true;
}
row += rowIncrement;
col += colIncrement;
return foundQueenOnPath(row, col, rowIncrement, colIncrement);
}
static void Main(string[] args)
{
var row = 0;
var col = 0;
for (; row < gridSize; row += 1)
{
for (; col < gridSize; col += 1)
{
Console.WriteLine(string.Join(", ", queens));
if (validPosition(row, col))
{
queens[row] = col;
col = 0;
break;
}
// reached the end without placing a queen.
if (col == gridSize - 1)
{
queens[row] = -1;
row += -1;
if(row < 0)
{
return;
}
col = queens[row] - 1;
}
}
Console.WriteLine(string.Join(", ", queens));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment