Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Linq;
- using System.Collections.Generic;
- namespace CSharp_Shell
- {
- public static class Program
- {
- static void printBoard(string [, ] board) {
- for (int i = 0; i < 4; i++) {
- for (int j = 0; j < 4; j++) {
- Console.Write(board[i, j] + " ");
- }
- Console.Write("\n");
- }
- }
- static bool checkIfSafe(string [,] board, int row, int col)
- {
- //check if all cols in current row are safe
- for(int i = col; i < 4; i++)
- {
- if(board[row, i] == "Q")
- {Console.WriteLine("This row is not safe");
- return false;}
- }
- //check all rows in current col
- for(int i = row; i < 4; i++)
- {
- if(board[i, col] == "Q"){
- Console.WriteLine("This col is not safe");
- return false;}
- }
- //check diagonals to the left\
- for(int i = row, j = col; i >= 0 && j >= 0; i--, j--)
- {
- if(board[i, j] == "Q"){
- Console.WriteLine("Left Diag not safe");
- return false;}
- }
- //check diagonals to the right
- for(int i = row, j = col; i < 4 && j < 4; i++, j++)
- {
- if(board[i, j] == "Q")
- {Console.WriteLine("Right Diag not safe");
- return false;}
- }
- //check diagonals to the left downwards
- for(int i = row, j = col; i < 4 && j >= 0; i++, j--)
- {
- if(board[i, j] == "Q")
- {Console.WriteLine("Left Diag downwards not safe");
- return false;}
- }
- //check diagonals to the right upwards
- for(int i = row, j = col; i >= 0 && j < 4; i--, j++)
- {
- if(board[i, j] == "Q")
- {Console.WriteLine("Right Diag upwards not safe");
- return false;}
- }
- //check directly upwards
- for(int i = row; i >= 0; i-- )
- {
- if(board[i, col] == "Q")
- { Console.WriteLine("Upside not safe");
- return false;}
- }
- //check directly left
- for(int i = col; i >= 0; i-- )
- {
- if(board[row, i] == "Q")
- { Console.WriteLine("Left not safe");
- return false;}
- }
- return true;
- }
- static bool Solve8queen(string[,] board, int col)
- {
- //base case
- if(col >= 4)
- {
- //return true;
- printBoard(board);
- return true;
- }
- //loop over the rows in the current col
- bool res = false;
- for(int i = 0; i < 4; i++)
- {
- if(board[i, col] == "Q"){
- // i ++;
- col = 0;
- Console.WriteLine("row " + i + " col " + col + " is occupied");
- }
- if(checkIfSafe(board, i, col))
- {
- //place queen
- board[i, col] = "Q";
- //explore other solns
- res = Solve8queen(board, col + 1) || res;
- //backtrack
- board[i, col] = ".";
- }
- else
- {
- //col++;
- }
- }
- return false;
- }
- public static void Main()
- {
- string[,] board = {
- {".", "Q", ".", "."},
- {".", ".", ".", "."},
- {".", ".", ".", "."},
- {".", ".", ".", "."}
- };
- //Console.WriteLine(checkIfSafe(board, 0, 1));
- Solve8queen(board, 0);
- //printBoard(board);
- //Console.WriteLine(checkIfSafe(board, 0, 2));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement