Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 79c0a2d

Browse files
authored
Added N Queens 2 problem for Backtracking concept in Cpp. (#919)
* added nqueens2 * added bfs hard prob
1 parent 231e28a commit 79c0a2d

File tree

2 files changed

+139
-0
lines changed

2 files changed

+139
-0
lines changed

C++/Backtracking/NQueens_2.cpp

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
int n;
4+
5+
int queen[20]; // to store the ith queen pos (ith queen pos => col num in which its saved)
6+
7+
bool check(int row,int col){
8+
// here we have to check from 0 to row whether any queen(queen[row]) can attk the cur level
9+
for(int i=0;i<row;i++){
10+
int pre_row=i;
11+
int pre_col=queen[i];
12+
13+
// rows cant collide so chill
14+
// checking for cols: if any pre_col and present col are same, then collision so not crt
15+
16+
// other is checking diagonally : syntax is abs(row-pre_row)==abs(col-pre_col)
17+
// checking whether distance btw 2 rows are same and 2 cols are same :if same then
18+
// there is a common diagonal btw them i.e 45 degrees
19+
// why abs means slope can be pos or negative
20+
if(pre_col==col or abs(row-pre_row)==abs(col-pre_col)) return false;
21+
}
22+
return true;
23+
}
24+
int rec(int level){
25+
// here rec means that the the number of ways a queen can be positioned
26+
//from this level(row) to last level(nth)
27+
28+
// base case
29+
if(level==n) {
30+
for(auto x:queen) cout<<x+1<<" ";
31+
cout<<endl;
32+
return 1;}
33+
// means u have crossed from 0 to n-1 rows and came out of board , so u made an arrangement
34+
// return 1 for the this arrangement count
35+
36+
// exploring and computation
37+
int ans=0;
38+
//going for all the choices
39+
for(int col=0;col<n;col++){
40+
// validation of the choices
41+
42+
// calling a check function as to decide a queen in the cur level,we need the information of the
43+
// previous arrangement queens to check if the cur queen can be attacked by them or not;
44+
if(check(level,col)){
45+
// if valid : store in queen arrays
46+
queen[level]=col;
47+
// moving to next
48+
ans+=rec(level+1);
49+
50+
// while backtracking, changes made above should be reverted
51+
queen[level]=-1;
52+
}
53+
}
54+
// return the ans;
55+
return ans; // no of ways to position remaining queens from cur level/ row
56+
}
57+
int main(){
58+
cin>>n; // how many N X N chess board
59+
memset(queen,-1,sizeof(queen));
60+
cout<<rec(0);
61+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// **OBSERVATIONS**
2+
// 1. Given that we can **jump to the previous and next neighbour if they are within the limits** from the current position.
3+
// 2. We can also **jump to the same element which is present in the array but at different index** .
4+
5+
// Atlast we have to return the **minimum number of steps to reach the end (n-1 th index )**
6+
7+
// **LOGIC**
8+
// **1**. Here we are using BFS Algorithm.
9+
// Then the immediate question is why????
10+
11+
// **Reason**
12+
13+
// **Whenever there is an unwieghted graph and we want to retrive the shortest path or minimum steps to reach the destination** , we use **BFS** , **as it takes all the neighbouring guys from the current node and this process repeats for every node** .
14+
15+
// **Thus the total visualisation will be like we are generating hotspots/ rainbows on each node. Therefore the spread to the entire graph takes minimum effort** .
16+
17+
// Thus , by moving forward
18+
// **2**. The question is very easy but few changes to be made on applying BFS.
19+
// **3**. According to Observations, here **for the current element its friends are the previous and next neighbours, and same guys** .
20+
// So we will create **a hashmap of node and his same guys**
21+
22+
// The other data structures needed are :- ***queue :- Pushing the indexes ;
23+
// Visited array (bool type ) :- To mark which nodes are visited***
24+
// And a **step variable** :- Counts the steps to till we have reach the end.
25+
// **4**. Starting the BFS, push 0 as its the first index and mark it as visted. Begin the loop until the queue becomes empty :
26+
// * Take the **front element** . **If its the n-1 th index , directly return the step** ;
27+
// * **Else take its previous and next guys and put in its friends list** ;
28+
// * Start **traversing the neighbours list which contains same guys, prev guy and next guy**.
29+
// * If they are **within the range and still not visited** :- Mark them as visited and push them
30+
31+
// **One important point of this whole question is, after visiting the neighbours list, plz clear the list** The reason is :
32+
33+
// **Removing the visited ones to reduce the repetitive work;
34+
// As the children are already visted and no use for the coming iterations for
35+
// any further guy in coming iterations bcz we have already used that path and didnt got the answer ,so not allowing to use this path**
36+
37+
// " **To tell in simple manner, everytime we are reducing the size of the friendslist, so that the search space is reducing.** "
38+
39+
// *Code*
40+
// ```
41+
#include<bits/stdc++.h>
42+
using namespace std;
43+
class Solution {
44+
public:
45+
int minJumps(vector<int>& arr) {
46+
int n=arr.size();
47+
if(n==1) return 0; // edge case : )
48+
unordered_map<int,list<int>>mp; // ele -> all its same guys
49+
for(int i=0;i<n;i++) mp[arr[i]].push_back(i);
50+
queue<int>q;
51+
vector<bool>vis(n,false);
52+
q.push(0); vis[0]=true;
53+
int step=0;
54+
while(!q.empty()){
55+
56+
int sz=q.size();
57+
while(sz--){
58+
int fr=q.front(); q.pop();
59+
if(fr==n-1) return step; // if u reached the last ind then return count step;
60+
// else now vist all its neighs who are i+1,i-1 and same guys
61+
list<int>& neigh=mp[arr[fr]];
62+
neigh.push_back(fr-1);
63+
neigh.push_back(fr+1);
64+
// since the left and right guys of ith ele are not there in its list
65+
66+
// so now iterate through neigh who are within the range and not vis
67+
for(auto x: neigh){
68+
if(x>=0 and x<n and !vis[x]){q.push(x); vis[x]=true;}
69+
}
70+
neigh.clear(); // removing the visited ones to reduce the reptiive work;
71+
// as the children are already visted and no use for the coming iterations for
72+
// any further guy in coming iterations; bcz we have already used that path and didnt got the ans ,so not allowing to use this path;
73+
}
74+
step++; // counting the steps
75+
}
76+
return 0;
77+
}
78+
};

0 commit comments

Comments
 (0)