Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- public class NQueens {
- public class Position {
- int x;
- int y;
- public Position(int i, int j) {
- x = i;
- y = j;
- }
- public bool canPlace(Position other) {
- return x != other.x && y != other.y && Math.Abs(x - other.x) != Math.Abs(y - other.y);
- }
- public String toString() {
- return "(" + x + "," + y + ")";
- }
- }
- public static Position position(int i, int j) {
- return new Position(i, j);
- }
- public bool isValid(Position prospect, List<Position> solution) {
- foreach (Position position in solution) {
- if (!prospect.canPlace(position)) {
- return false;
- }
- }
- return true;
- }
- public List<Position> nextColPositions(int col, int n, List<Position> solution) {
- List<Position> ret = new List<Position>();
- Position temp;
- for (int i = 0; i < n; i++) {
- temp = position(i, col);
- if (isValid(temp, solution)) {
- ret.Add(temp);
- }
- }
- return ret;
- }
- public List<List<Position>> solve(int col, int n, List<List<Position>> solutions) {
- List<List<Position>> result = new List<List<Position>>();
- if (col >= n) {
- return solutions;
- } else {
- List<Position> prospects;
- List<Position> temp = null;
- foreach (List<Position> solution in solutions) {
- prospects = nextColPositions(col, n, solution);
- foreach (Position p in prospects) {
- temp = new List<Position>(solution);
- temp.Add(p);
- result.Add(temp);
- }
- solution.Clear();
- }
- solutions.Clear();
- return solve(col + 1, n, result);
- }
- }
- public void nqueens(int n) {
- List<List<Position>> input = new List<List<Position>>();
- input.Add(new List<Position>());
- List<List<Position>> solutions = solve(0, n, input);
- Console.WriteLine("No. of Solutions for n = " + n + " : " + solutions.Count);
- }
- public static void Main(string[] args) {
- int n = 13;
- for (int i = 0; i <= n; i++) {
- var timer = System.Diagnostics.Stopwatch.StartNew();
- new NQueens().nqueens(i);
- timer.Stop();
- Console.WriteLine("Time taken(ms) : " + timer.ElapsedMilliseconds);
- }
- Console.WriteLine("Poop");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement