-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12.Recursion + Backtracking.cpp
More file actions
1577 lines (1360 loc) · 41.7 KB
/
Copy path12.Recursion + Backtracking.cpp
File metadata and controls
1577 lines (1360 loc) · 41.7 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
//! binary tree structure
struct Node{
int data;
Node *left;
Node *right;
Node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
//! Recursion is the process in which a function calls itself until a base condition is reached.
//~ a base condition is a condition where the recursion stops.
//~ recursion means repeating the same thing again and again.
//! print 1 to n using recursion
//? Yes, for a void function, it does not return anything, and the base case just stops execution.
void print(int n){
// base condition where the recursion stops
// stop condition
// if we print n inside the base case it will print our last recursion
// condition in which we have to stop
if (n == 0)
return;
// elements will be printed in decreasing order 5 4 3 2 1
// first element will be printed
cout << n << " ";
// recursive call
// element printed in incresing order 1 2 3 4 5
// after the recursive call element will be printed
print(n - 1);
// printitng the current n number
}
//! for an int function, the base case must return a value, which can then be used in recursive calls.
int print1toN(int n){
//? when base case hit it will return base case base case will print at new line
if (n == 0)
return 0; // Base case returns 0
//? call the recursive function and the print the current condition recursive call
return print1toN(n - 1); // Recursive call returns something
// print 5 and return for 5-1 = 4 print : 5
// print 4 and return for 4-1 = 3 print : 5 4
// print 3 and return for 3-1 = 2 print : 5 4 3
// print 2 and return for 2-1 = 1 print : 5 4 3 2
// print 1 and return for 1-1 = 0 print : 5 4 3 2 1
// print 0 and return for 0-1 = -1 print : 5 4 3 2 1 0
cout << n << " "; // Print the current number
}
//! factorial using recursion
int fact(int n){
// base case
if (n == 0 || n == 1)
return 1;
// recursive call
return n * fact(n - 1);
}
//! height of binary tree using recursion
int height(Node *root){
// base case
if (root == NULL)
return 0;
// left height recursive call goes upto the leaf node
int leftHeight = height(root->left);
// right height recursive call goes upto the leaf node
int rightHeight = height(root->right);
// return the max in between left and right height
return max(leftHeight, rightHeight) + 1;
}
//! sort an array using recursion and insert element using loop
void sort(int arr[], int n){
// base case
if (n == 1)
return;
// hypothesis
sort(arr, n - 1);
// induction
int lastElement = arr[n - 1];
int j = n - 2;
while (j >= 0 && arr[j] > lastElement)
{
// shifting the elements
arr[j + 1] = arr[j];
j--;
}
// last element will be inserted at the correct position
arr[j + 1] = lastElement;
}
//! both insert element and sort array using recursion
void insert(vector<int> &arr, int temp){
if (arr.empty() || arr.back() <= temp)
{
arr.push_back(temp);
return;
}
// recursion happend for removing the last element of array
// it will run unitl the base case hit
int last = arr.back();
arr.pop_back(); // Remove last element
insert(arr, temp); // Recursive call to insert temp in the reduced array
// this will only run when the base case hit
arr.push_back(last); // Push back the removed element
}
void sortArray(vector<int> &arr){
if (arr.size() <= 1)
return; // Base case
int temp = arr.back();
arr.pop_back(); // Remove last element
sortArray(arr); // Recursively sort remaining array
insert(arr, temp); // Insert the removed element in sorted order
}
//! sort stack using recursion
void insertElement(stack<int> &st, int top)
{
if (st.empty() || st.top() <= top)
{
st.push(top);
return;
}
int temp = st.top();
st.pop();
insertElement(st, top);
st.push(temp);
}
// remove the element from stck until the last element left
// since the last element is itself smallest element largest element and sorted
// since its a single element
void sortStack(stack<int> &st)
{
if (st.empty())
return;
int top = st.top();
st.pop();
sortStack(st);
insertElement(st, top);
} //^ tc : O(n^2) sc : O(n)
//! Delete the middle element of the stack using recursion
void deleteMiddleElement(stack<int> &st, int k)
{
if (k == 1)
{
st.pop();
return;
}
int temp = st.top();
st.pop();
deleteMiddleElement(st, k - 1);
st.push(temp);
}
//! Revere stack using recursion
void insertAtBottom(stack<int> &st, int top)
{
// Base case
if (st.empty())
{
st.push(top);
return;
}
// recursion step
int temp = st.top();
st.pop();
insertAtBottom(st, top);
// works after the base case hit
st.push(temp);
// Push 5
// Insert 4 → removes 5, pushes 4, then 5
// Insert 3 → removes 4, 5, pushes 3, then 4, 5
// Insert 2 → removes 3, 4, 5, pushes 2, then 3, 4, 5
// Insert 1 → removes 2, 3, 4, 5, pushes 1, then 2, 3, 4, 5
}
void reverseStack(stack<int> &st)
{
// Base case
if (st.size())
return;
// recursion step
int temp = st.top();
st.pop();
reverseStack(st);
// Recursive Calls of reverseStack(st)
// Remove 1
// Remove 2
// Remove 3
// Remove 4
// Remove 5
// Now stack is empty.
// excute after the base case hit
insertAtBottom(st, temp);
}
//! K-th symbol in grammar
void kthSymbol(int n, int k){
if (n == 1 && k == 1)
{
cout << 0 << endl;
return;
}
int mid = pow(2, n - 1) / 2;
if (k <= mid)
{
kthSymbol(n - 1, k);
}
else
{
kthSymbol(n - 1, k - mid);
}
}
//! Tower of Hanoi
void towerOfHanoi(int n, char a, char b, char c)
{
if (n == 1)
{
cout << "Move 1 from " << a << " to " << c << endl;
return;
}
towerOfHanoi(n - 1, a, c, b);
cout << "Move " << n << " from " << a << " to " << c << endl;
towerOfHanoi(n - 1, b, a, c);
}
//! String to integer stringAtoi
int stringAtoi(string str, int n)
{
if (n == 0)
return 0;
// Extract the last digit from the string
// n - 1 is pointing the last element of the string
// from minusing the '0' we get the integer value of the string
int digit = str[n - 1] - '0';
// recursive call
// decrease the size of the string by 1
int smallAns = stringAtoi(str, n - 1);
// stringAtoi("1234") -> calls stringAtoi("123")
// stringAtoi("123") -> calls stringAtoi("12")
// stringAtoi("12") -> calls stringAtoi("1")
// stringAtoi("1") -> calls stringAtoi("") // Base case (returns 0)
// after reaching the base case it will start returning the value
// Returning and Multiplication Starts (Unwinding)
// return 0 * 10 + 1 = 1
// return 1 * 10 + 2 = 12
// return 12 * 10 + 3 = 123
// return 123 * 10 + 4 = 1234
return smallAns * 10 + digit;
}
//! Count good numbers
// brute force
// #define MOD 1000000007
// int countGoodNumbers(long long n)
// {
// long long count = 0;
// for (long long i = 1; i <= n; i++)
// {
// if (i % 2 == 0)
// count = (count * 4) % MOD;
// else
// count = (count * 5) % MOD;
// }
// return count;
// }
//! Optimized solution using recursion TC : O(logn)
class Solution{
public:
const int MOD = 1e9 + 7;
long long power(long long base, long long exp)
{
// we are incresing the base as even power to the exp
// each recursion we are dividing it by 2 to we can reduce the exponet
// ones the exponent become 0 or 1 we can return 1 since 1^0 = 1
if (exp == 0)
return 1; // Base case: anything^0 = 1
// recursion step minimizing the exponent
long long half = power(base, exp / 2); // base = 5 and exponet 2/2=0
// storing the result by multiplying it with itself get the mod to
// reduce the answer size
long long result = (half * half) % MOD; // 5^2 = 25 4^2 = 16
if (exp % 2)
result = (result * base) % MOD; // If odd, multiply once more
return result;
}
int countGoodNumbers(long long n)
{
// get the total number or even places in n
long long evenPos = (n + 1) / 2; // Number of even positions
// get the total number of odd position in n
long long oddPos = n / 2; // Number of odd positions
// call the recursive power function to multiply the 5 with total number
// of even positions in n = 4 (4+1)/2 5/2 = 2 even index in n odd
// positions in n = 4 4/2 = 2 odd index in n
return (power(5, evenPos) * power(4, oddPos)) % MOD;
}
};
//! Generate all binary strings without consecutive 1's
void generateBinaryStrings(int n, string s, char last)
{
// base condition
if (n == 0){
cout << s << endl;
return;
}
generateBinaryStrings(n - 1, s + "0", '0'); // Always include '0'
if (last != '1')
generateBinaryStrings(n - 1, s + "1", '1'); // Include '1' only if the last was not '1'
}
//! Generate Parenthesis using Recursion
class parenthesis{
public:
//! first approach using recursion and backtracking
vector<string> result;
bool isvalid(string s){ // o(n) time complexity sc : O(1)
int balance = 0;
for(char c : s){
if(c == '('){
balance++;
}else{
balance--;
}
if(balance < 0){
return false;
}
}
return balance == 0;
}
void generate(string& s, int n){
// how many time recursion will work so the total number of combination are 2*n
// suppose the value of n = 2 so the total combination will be 2*2 = 4
// base case
if(s.size() == 2*n){
// checking the valid parenthesis
if(isvalid(s)){
result.push_back(s);
}
return;
}
// typical backtracking first try all possible open bracket then close bracket
// recursive call first try for open bracket
s.push_back('(');
generate(s, n);
s.pop_back(); // undo for the open bracket
// recursive call second try for close bracket
s.push_back(')');
generate(s, n);
s.pop_back(); // undo for the close bracket
}
vector<string> generatepararenthesis(int n){
// time complexity : O(2^n) sc : O(2^n)
string s = "";
generate(s , n);
return result;
}
//! Second Approach only using recursion
//! more simple solution using recursion plus open and close bracket logic
string generateallpossible(int open, int close, string s)
{
// base case
if (open == 0 && close == 0)
{
result.push_back(s);
return s;
}
// recursive call
if (open > 0)
{
generateallpossible(open - 1, close, s + "(");
}
if (close > open)
{
generateallpossible(open, close - 1, s + ")");
}
return s;
}
// time complexity : O(2^n) sc : O(2^n) just remove the extra of O(n) required for
// checking the valid parenthesis
};
//! Print all Subset of a string using recursion
void solve(string input, string output){
// base case
if(input.size() == 0){
cout << output << endl;
return;
}
// we are not including input char
string output1 = output;
// we are including input char
string output2 = output;
// since we are taking input push input into the output 2
output2.push_back(input[0]);
// now remove it from the input //-abc -> bc -> c -> ""
input.erase(input.begin() + 0);
// now call for not adding
solve(input, output1); //
// now call for adding
solve(input, output2);
}
string subset(string input){
string output = "";
solve(input, output);
return output; // Tc : O(2^n) Sc : O(2^n)
}
//! subset of the number using recursion
class Subsets{
public:
void solve(vector<int> &nums, int idx, vector<int> &temp, vector<vector<int>> &result)
{
// idex goes to out of bound then we return the temp
if (idx >= nums.size())
{
result.push_back(temp);
return;
}
// firse we include the element in the temp
temp.push_back(nums[idx]);
// recursive call
solve(nums, idx + 1, temp, result);
// then we remove the element from the temp
temp.pop_back();
// recursive call
solve(nums, idx + 1, temp, result);
}
vector<vector<int>> subsets(vector<int> &nums)
{
vector<int> temp;
vector<vector<int>> result;
solve(nums, 0, temp, result);
return result;
}
};
//! total number of subsequences that sum equal to k
void countSubsequence(vector<int> & arr, int k , int index, int sum , vector<vector<int>> &result, vector<int> &temp){
if(index == arr.size()){
if(sum == k){
result.push_back(temp);
}
return;
}
// add the element in the temp
temp.push_back(arr[index]);
// add in the sum
sum += arr[index];
// recursive call
countSubsequence(arr, k, index + 1, sum, result, temp);
// remove the element from the temp
temp.pop_back();
// remove the sum
sum -= arr[index];
// recursive call
countSubsequence(arr, k, index + 1, sum, result, temp);
// time complexity : O(2^n) sc : O(2^n) since we are storing all the possible combination in worst we might have to store all the possible combination
}
//! subset sum problem
//! Problem statement
// You are given an array 'A' of 'N' integers. You have to return true if there exists a subset of elements of 'A' that sums up to 'K'. Otherwise, return false.
bool solve(vector<int>& a, int k, int index, int sum) {
if (index == a.size()) {
return sum == k; // Return true if we find a valid subset
}
// Take the element
if (solve(a, k, index + 1, sum + a[index])) {
return true;
}
// Not take the element
if (solve(a, k, index + 1, sum)) {
return true;
}
return false; // No valid subset found
}
bool isSubsetPresent(int k, vector<int> &a)
{
// Write your code here
return solve(a, k , 0, 0);
}
//! combination sum I
// find all the combination of the element that sum up to the target
// Input: candidates = [2,3,6,7], target = 7
// Output: [[2,2,3],[7]]
class Combination_Sum
{
public:
void solve(vector<int> &candidates, int target, int ind, vector<int> &temp,
vector<vector<int>> &result)
{
if (target == 0)
{
result.push_back(temp);
return;
}
if (target < 0 || ind >= candidates.size())
return;
// Include the current element
temp.push_back(candidates[ind]);
solve(candidates, target - candidates[ind], ind, temp, result);
temp.pop_back();
// Exclude the current element and move to the next index
solve(candidates, target, ind + 1, temp, result);
}
vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
vector<int> temp;
vector<vector<int>> result;
solve(candidates, target, 0, temp, result);
return result;
}
};
//! combination sum II
// Input: candidates = [10,1,2,7,6,1,5], target = 8
// Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
void solve(vector<int> &candidates, int target, int ind, vector<int> &temp,
vector<vector<int>> &result)
{
if (target == 0)
{
result.push_back(temp);
return;
}
for(int i = ind; i < candidates.size(); i++){
if(i > ind && candidates[i] == candidates[i - 1]){
continue;
}
if(target - candidates[i] < 0){
break;
}
temp.push_back(candidates[i]);
solve(candidates, target - candidates[i], i + 1, temp, result);
temp.pop_back();
}
// // Include the current element
// temp.push_back(candidates[ind]);
// solve(candidates, target - candidates[ind], ind + 1, temp, result);
// temp.pop_back();
// // Skip the duplicates
// while (ind + 1 < candidates.size() && candidates[ind] == candidates[ind + 1])
// ind++;
// // Exclude the current element and move to the next index
// solve(candidates, target, ind + 1, temp, result);
}
vector<vector<int>> combinationSum2(vector<int> &candidates, int target)
{
sort(candidates.begin(), candidates.end());
vector<int> temp;
vector<vector<int>> result;
solve(candidates, target, 0, temp, result);
return result;
}
//! Subset Sums I
// Given a array arr of integers, return the sums of all subsets in the list. Return the sums in any order
// Input: arr = [1, 2, 3] Output: [0, 1, 2, 3, 4, 5, 6]
class Subset_Sums_every_possible_combination
{
public:
void solve(vector<int> &arr, int ind, int sum, vector<int> &result)
{
if (ind == arr.size())
{
result.push_back(sum);
return;
}
sum += arr[ind];
solve(arr, ind + 1, sum, result);
sum -= arr[ind];
solve(arr, ind + 1, sum, result);
}
vector<int> Sums(vector<int> &arr)
{
// code here
vector<int> result;
solve(arr, 0, 0, result);
sort(result.begin(), result.end());
return result;
}
};
//! 90 subset II
void solve(vector<int>& nums, int index, vector<int> &temp, vector<vector<int>> &result)
{
result.push_back(temp);
for (int i = index; i < nums.size(); i++)
{
if (i > index && nums[i] == nums[i - 1]) continue;
temp.push_back(nums[i]);
solve(nums, i + 1, temp, result);
temp.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums)
{
vector<int> temp;
vector<vector<int>> result;
sort(nums.begin(), nums.end());
solve(nums, 0, temp, result);
return result;
}
//! combination sum III
class Combination_Sum_III
{
public:
void solve(int n, int k, int index, int sum, vector<int> &temp,
vector<vector<int>> &result)
{
if (index > 9)
{
if (sum == n && temp.size() == k)
{
result.push_back(temp);
}
return;
}
temp.push_back(index);
solve(n, k, index + 1, sum + index, temp, result);
temp.pop_back();
solve(n, k, index + 1, sum, temp, result);
}
vector<vector<int>> combinationSum3(int k, int n)
{
vector<int> temp;
vector<vector<int>> result;
solve(n, k, 1, 0, temp, result);
return result;
}
};
//! Letter Combinations of a Phone Number
class Letter_Combinations
{
public:
vector<string> result;
void solve(int idx, string &digits, string &temp, unordered_map<char, string> &mp)
{
if (idx >= digits.length())
{
result.push_back(temp);
return;
}
char ch = digits[idx];
string str = mp[ch];
for (int i = 0; i < str.length(); i++)
{
// Do
temp.push_back(str[i]);
solve(idx + 1, digits, temp, mp);
temp.pop_back();
}
}
vector<string> letterCombinations(string digits)
{
if (digits.length() == 0)
return {};
unordered_map<char, string> mp;
mp['2'] = "abc";
mp['3'] = "def";
mp['4'] = "ghi";
mp['5'] = "jkl";
mp['6'] = "mno";
mp['7'] = "pqrs";
mp['8'] = "tuv";
mp['9'] = "wxyz";
string temp = "";
solve(0, digits, temp, mp);
return result;
}
};
//^ Hard Problem
//! palindrome partitioning
class palindrome_partitioning{
public:
vector<vector<string>> result;
bool ispalindrome(string s, int start, int end){
while(start < end){
if(s[start] != s[end]){
return false;
}
start++;
end--;
}
return true;
}
void solve(string s, int index, vector<string> &temp){
if(index == s.size()){
result.push_back(temp);
return;
}
for(int i = index; i < s.size(); i++){
if(ispalindrome(s, index, i)){
temp.push_back(s.substr(index, i - index + 1));
solve(s, i + 1, temp);
temp.pop_back();
}
}
}
vector<vector<string>> partition(string s){
vector<string> temp;
solve(s, 0, temp);
return result;
}
// time complexity : O(n*2^n) sc : O(n)
};
//! Word Search
/*Space Complexity: O(L)
Time Complexity: O(M * N * 3^L)
Space Complexity is because of recursion - to store function stack context.
Time Complexity - from every block we go in three adjacent blocks (avoiding the direction we came from).
This walk can go for max of L times. So each thred at most goes L length long. -> O(3^L).
Now this is applied at each node from main calling function -> O(M * N). Therefore, O(M * N * 3^L).
*/
class Word_Search
{
public:
int l, m, n;
vector<vector<int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool find(vector<vector<char>> &board, int i, int j, string &word, int idx)
{
if (idx >= l)
return true;
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[idx])
return false;
char temp = board[i][j];
board[i][j] = '$';
for (auto &dir : directions)
{
int i_ = i + dir[0];
int j_ = j + dir[1];
if (find(board, i_, j_, word, idx + 1))
return true;
}
board[i][j] = temp;
return false;
}
bool exist(vector<vector<char>> &board, string word)
{
m = board.size();
n = board[0].size();
l = word.length();
if (m * n < l)
return false;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (board[i][j] == word[0] && find(board, i, j, word, 0))
{
return true;
}
}
}
return false;
}
};
//! N-Queens problems
// Approach-1 (Simple dfs)
// T.C : O(N!) - Read the reason above
// S.C : O(N) to store the result
class N_Queens
{
public:
vector<vector<string>> result;
bool isValid(vector<string> &board, int row, int col)
{
// look for up
for (int i = row; i >= 0; i--)
{
if (board[i][col] == 'Q')
return false;
}
// check left diagonal upwards
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (board[i][j] == 'Q')
return false;
}
// check right diagonal upwards
for (int i = row, j = col; i >= 0 && j < board.size(); i--, j++)
{
if (board[i][j] == 'Q')
return false;
}
/*
Wait a second, Why didn't I check any squares downwards ???
If you notice, every time I am calling dfs(board, row+1); i.e. after
placing a Queen at a row, I move down. So, It's guaranteed I will
not get any Queen downwards.
Example :
For n = 4
_ _ _ Q (Put int the first row)
Q _ _ _ (While putting here, I only need to see
above of me because I have not populated any Q in downwards) _ _ Q
_ (Same, While putting here, I only need to see above of me
because I have not populated any Q in downwards)
So, on
*/
return true;
}
void solve(vector<string> &board, int row)
{
if (row == board.size())
{
result.push_back(board);
return;
}
/*
place one queen at every row and check before placing
in every directions where there is risk if being attackes
i.e. up, diagonally because we are placing queens from
top row to bottom row, so we need to check if we put a queen
vertically up in some row or diagonally upwards in some row
*/
for (int i = 0; i < board.size(); i++)
{
if (isValid(board, row, i))
{
board[row][i] = 'Q';
solve(board, row + 1);
board[row][i] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n)
{
if (n == 0)
return {};
vector<string> board(n, string(n, '.'));
// For, n = 3, board = {"...", "...", "..."} initially
solve(board, 0);
return result;
}
};
//! word search problem
// Space Complexity: O(L)
// Time Complexity: O(M * N * 3^L)
class word_search
{
public:
int l, m, n;
vector<vector<int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool find(vector<vector<char>> &board, int i, int j, string &word, int idx)
{
if (idx >= l)
return true;
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[idx])
return false;
char temp = board[i][j];
board[i][j] = '$';
for (auto &dir : directions)
{
int i_ = i + dir[0];
int j_ = j + dir[1];
if (find(board, i_, j_, word, idx + 1))
return true;
}
board[i][j] = temp;
return false;
}
bool exist(vector<vector<char>> &board, string word)
{
m = board.size();
n = board[0].size();
l = word.length();