Skip to content

Commit b8cfc88

Browse files
Merge pull request #33 from akshaysoni10/LeetCode-Solution
N-Queen solution updated
2 parents d0cf709 + 97436d7 commit b8cfc88

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

Convert_Sorted_Array_To_BST.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public:
3+
TreeNode* solve(vector<int> &nums, int start, int end){
4+
//base case
5+
if(start > end){
6+
return NULL;
7+
}
8+
9+
int mid = (start + end)/2;
10+
TreeNode* temp = new TreeNode(nums[mid]);
11+
12+
temp -> left = solve(nums, start, mid-1);
13+
temp -> right = solve(nums, mid+1, end);
14+
return temp;
15+
}
16+
17+
TreeNode* sortedArrayToBST(vector<int>& nums) {
18+
return solve(nums, 0, nums.size()-1);
19+
}
20+
};

Intersection_of_Two_LL.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
4+
ListNode* a = headA, *b = headB;
5+
while(a != b){
6+
if(a == NULL){
7+
a = headB;
8+
}
9+
else{
10+
a = a -> next;
11+
}
12+
13+
if(b == NULL){
14+
b = headA;
15+
}
16+
else{
17+
b = b -> next;
18+
}
19+
}
20+
return a;
21+
}
22+
};

N_Queen.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
void solve(int col, vector<string> &board, vector<vector<string>> &ans, vector<int> &leftRow, vector<int> &upperDiagonal, vector<int> &lowerDiagonal, int n){
4+
//base case
5+
if(col == n){
6+
ans.push_back(board);
7+
return;
8+
}
9+
10+
for(int row=0; row<n; row++){
11+
if(leftRow[row] == 0 && lowerDiagonal[row + col] == 0 && upperDiagonal[n-1 + col - row] == 0){
12+
board[row][col] = 'Q';
13+
leftRow[row] = 1;
14+
lowerDiagonal[row + col] = 1;
15+
upperDiagonal[n-1 + col - row] = 1;
16+
solve(col + 1, board, ans, leftRow, upperDiagonal, lowerDiagonal, n);
17+
board[row][col] = '.';
18+
leftRow[row] = 0;
19+
lowerDiagonal[row + col] = 0;
20+
upperDiagonal[n-1 + col - row] = 0;
21+
}
22+
}
23+
}
24+
25+
vector<vector<string>> solveNQueens(int n) {
26+
vector<vector<string>> ans;
27+
vector<string> board(n);
28+
string s(n, '.');
29+
for(int i=0; i<n; i++){
30+
board[i] = s;
31+
}
32+
vector<int> leftRow(n, 0), upperDiagonal(2 * n - 1, 0), lowerDiagonal(2 * n - 1, 0);
33+
solve(0, board, ans, leftRow, upperDiagonal, lowerDiagonal, n);
34+
return ans;
35+
}
36+
};

0 commit comments

Comments
 (0)