Advertisement
vencinachev

Day3NQueens

Sep 5th, 2019
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.12 KB | None | 0 0
  1. using System;
  2.  
  3. namespace NQP
  4. {
  5.     class Program
  6.     {
  7.         static int N;
  8.         static int k = 1;
  9.  
  10.         static void PrintSolution(int[,] board)
  11.         {
  12.             Console.WriteLine("{0} - ", k++);
  13.             for (int i = 0; i < board.GetLength(0); i++)
  14.             {
  15.                 for (int j = 0; j < board.GetLength(1); j++)
  16.                 {
  17.                     Console.Write("{0} ", board[i, j]);
  18.                 }
  19.                 Console.WriteLine();
  20.             }
  21.         }
  22.  
  23.  
  24.         static bool IsSave(int[,] board, int row, int col)
  25.         {
  26.             for (int i = 0; i < col; i++)
  27.             {
  28.                 if (board[row, i] == 1)
  29.                 {
  30.                     return false;
  31.                 }
  32.             }
  33.  
  34.             for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
  35.             {
  36.                 if (board[i, j] == 1)
  37.                 {
  38.                     return false;
  39.                 }
  40.             }
  41.  
  42.             for (int i = row, j = col; i < N && j >= 0; i++, j--)
  43.             {
  44.                 if (board[i, j] == 1)
  45.                 {
  46.                     return false;
  47.                 }
  48.             }
  49.             return true;
  50.         }
  51.        
  52.  
  53.  
  54.  
  55.        static bool SolveNQ(int[,] board, int col)
  56.         {
  57.             if (N == col)
  58.             {
  59.                 PrintSolution(board);
  60.                 return true;
  61.             }
  62.  
  63.             bool res = false;
  64.  
  65.             for (int i = 0; i < N; i++)
  66.             {
  67.                 if (IsSave(board, i, col))
  68.                 {
  69.                     board[i, col] = 1;
  70.                     res = SolveNQ(board, col + 1) || res;
  71.                     board[i, col] = 0;
  72.                 }
  73.             }
  74.             return res;
  75.         }
  76.  
  77.  
  78.         static void Main(string[] args)
  79.         {
  80.             Console.Write("Enter number of queens: ");
  81.             N = int.Parse(Console.ReadLine());
  82.             int[,] matrix = new int[N, N];
  83.             if(!SolveNQ(matrix, 0))
  84.             {
  85.                 Console.WriteLine("Solution does not exist!");
  86.             }
  87.            
  88.         }
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement