-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackTracking_01.java
More file actions
119 lines (95 loc) · 3.1 KB
/
Copy pathBackTracking_01.java
File metadata and controls
119 lines (95 loc) · 3.1 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
// Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
// Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
// Input: n = 4
// Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
// Input: n = 1
// Output: [["Q"]]
// Time Complexity: O(N!)
// Space Complexity: O(N^2)
import java.util.ArrayList;
import java.util.List;
public class BackTracking_01 {
public static void Save_Board(List<List<String>> All_Boards,char[][] Board){
List<String> New_Board = new ArrayList<>();
for(int i=0;i<Board.length;i++){
StringBuilder Row = new StringBuilder();
for(int j=0;j<Board[i].length;j++){
if(Board[i][j]=='Q'){
Row.append('Q');
}
else{
Row.append('.');
}
}
New_Board.add(Row.toString());
}
All_Boards.add(New_Board);
}
public static Boolean Queen_is_Safe(char[][] Board , int row ,int col){
// Vertical
for(int i=0;i<Board.length;i++){
if(Board[i][col]=='Q'){
return false;
}
}
// Horizontal
for(int i=0;i<Board[0].length;i++){
if(Board[row][i]=='Q'){
return false;
}
}
// Upper Left
int r=row;
for(int c=col; r>=0 && c>=0 ; r-- , c-- ){
if(Board[r][c]=='Q'){
return false;
}
}
// Upper Right
r=row;
for(int c=col; r>=0 && c<Board.length; r-- , c++){
if(Board[r][c]=='Q'){
return false;
}
}
// Lower Left
r=row;
for(int c=col ; r<Board.length && c>=0 ; r++ , c--){
if(Board[r][c]=='Q'){
return false;
}
}
// Lower Right
r=row;
for(int c=col; c<Board.length && r<Board.length ; r++ , c++){
if(Board[r][c]=='Q'){
return false;
}
}
return true;
}
public static void helper(List<List<String>> All_Boards,char[][] Board,int col){
if(col == Board.length){
Save_Board(All_Boards,Board);
return;
}
for(int row=0;row<Board.length;row++){
if(Queen_is_Safe(Board,row,col)){
Board[row][col]='Q';
helper(All_Boards, Board, col+1);
Board[row][col]='.';
}
}
}
public static List<List<String>> solveNQueens(int n){
List<List<String>> All_Boards=new ArrayList<>();
char[][] Board = new char[n][n];
helper(All_Boards,Board,0);
return All_Boards;
}
public static void main(String[] args) {
int n = 4;
System.out.println(solveNQueens(n));
}
}