-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnqueen.cpp
More file actions
123 lines (108 loc) · 2.35 KB
/
Copy pathnqueen.cpp
File metadata and controls
123 lines (108 loc) · 2.35 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
120
121
122
123
// Question : https://youtu.be/prZJ0hA43NU?list=PL-Jc9J83PIiFj7YSPl2ulcpwy-mwj1SSk
//Explanation : https://www.pepcoding.com/resources/online-java-foundation/recursion-backtracking/n_queens/topic
//Solution : https://youtu.be/05y82cP3bJo?list=PL-Jc9J83PIiFj7YSPl2ulcpwy-mwj1SSk
#include<string>
#include<vector>
#include<iostream>
using namespace std;
//Function to determine , the queen which we are placing right now on the cell is safe or not
bool isSafeLeft(int **arr,int i,int j,int n)
{
while(j>=0)
{
if(arr[i][j]==1)
return false;
j--;
}
return true;
}
bool isSafeUp(int **arr,int i,int j,int n)
{
while(i>=0)
{
if(arr[i][j]==1)
return false;
i--;
}
return true;
}
bool isSafeLeftDiagonal(int **arr,int i,int j,int n)
{
while(i>=0 && j>=0)
{
if(arr[i][j]==1)
return false;
i--;
j--;
}
return true;
}
bool isSafeRightDiagonal(int **arr,int i,int j,int n)
{
while(i>=0 && j<n)
{
if(arr[i][j]==1)
return false;
i--;
j++;
}
return true;
}
bool isSafe(int **arr,int i,int j,int n)
{
bool left=isSafeLeft(arr,i,j,n);
bool up=isSafeUp(arr,i,j,n);
bool ld=isSafeLeftDiagonal(arr,i,j,n);
bool rd=isSafeRightDiagonal(arr,i,j,n);
return left && up && ld && rd;
}
void placeQueens(int **arr,int i,int j,int n,vector<vector<int> > &ans,vector<int> temp)
{
if(i==n)
{
//we have placed all queens succesfully
if(!temp.empty())
ans.push_back(temp);
return;
}
else if(i<0 || j<0 || i>=n || j>=n)
return ;
else
{
if(isSafe(arr,i,j,n))
{
arr[i][j]=1;
temp.push_back(i);
temp.push_back(j);
placeQueens(arr,i+1,0,n,ans,temp);
temp.pop_back();
temp.pop_back();
arr[i][j]=0;
}
placeQueens(arr,i,j+1,n,ans,temp);
}
}
int main()
{
int n;
cin>>n;
int **arr=new int*[n];
for(int i=0;i<n;i++)
{
arr[i]=new int[n];
}
vector<vector<int> > ans;
vector<int> temp;
placeQueens(arr,0,0,n,ans,temp);
for(auto &v:ans)
{
int l=v.size();
int i=0;
while(i<l)
{
cout<<v[i]<<"-"<<v[i+1]<<", ";
i+=2;
}
cout<<".\n";
}
}