// C# program to implement 8 queen problem using System; class GfG { // Function to check if it is safe to place // the queen at board[row][col] static bool isSafe(int[,] mat, int row, int col) { int n = mat.GetLength(0); int i, j; // Check this col on upper side for (i = 0; i < row; i++) if (mat[i, col] == 1) return false; // Check upper diagonal on left side for (i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) if (mat[i, j] == 1) return false; // Check lower diagonal on left side for (i = row - 1, j = col + 1; j < n && i >= 0; i--, j++) if (mat[i, j] == 1) return false; return true; } static bool placeQueens(int row, int[,] mat) { int n = mat.GetLength(0); // base case: If all queens are placed // then return true if (row == n) return true; // Consider the row and try placing // queen in all columns one by one for (int i = 0; i < n; i++) { // Check if the queen can be placed if (isSafe(mat, row, i)) { mat[row, i] = 1; if (placeQueens(row + 1, mat)) return true; mat[row, i] = 0; } } return false; } // Function to find the solution // to the 8-Queens problem static int[,] queens() { int n = 8; // Initialize the board int[,] mat = new int[n, n]; placeQueens(0, mat); return mat; } static void Main() { int[,] res = queens(); int n = res.GetLength(0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(res[i, j] + " "); } Console.WriteLine(); } } }