-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGFG
More file actions
100 lines (82 loc) · 2.49 KB
/
GFG
File metadata and controls
100 lines (82 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
class NQueen
{
// Function to check if it is safe to place
static int isSafe(int[][] mat, int row, int col)
{
int n = mat.length;
int i, j;
// Check this col on upper side
for (i = 0; i < row; i++)
if (mat[i][col] == 1)
return 0;
// 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 0;
// Check upper diagonal on right side
for (i = row - 1, j = col + 1; j < n && i >= 0; i--, j++)
if (mat[i][j] == 1)
return 0;
return 1;
}
// Recursive function to place queens
static void placeQueens(int row, int[][] mat,
ArrayList<ArrayList<Integer>> result)
{
int n = mat.length;
// base case: If all queens are placed
if (row == n)
{
// store current solution
ArrayList<Integer> ans = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
ans.add(j + 1);
}
}
}
result.add(ans);
return;
}
// 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) == 1)
{
mat[row][i] = 1;
placeQueens(row + 1, mat, result);
// backtrack
mat[row][i] = 0;
}
}
}
// Function to find all solutions
static ArrayList<ArrayList<Integer>> nQueen(int n)
{
// Initialize the board
int[][] mat = new int[n][n];
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
// Place queens
placeQueens(0, mat, result);
return result;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of Queens: ");
int n =sc.nextInt();
ArrayList<ArrayList<Integer>> result = nQueen(n);
for (ArrayList<Integer> ans : result) {
for (int i : ans) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
Output: