-
Notifications
You must be signed in to change notification settings - Fork 1
/
Backtracking.txt
861 lines (755 loc) · 26.1 KB
/
Backtracking.txt
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
SOLUTIONS OF THESE QUESTIONS ARE EITHER ON GFG OR ON LEETCODE.
---------------------------------------BACKTRACKING-----------------------------------------
1. Rat in a Maze Problem
public static void RatMaze(int[][]maze,boolean[][]visited,int row,int col,String ans,ArrayList<String>list){
if(row==maze.length-1 && col==maze.length-1){
list.add(ans);
return;
}
if(row<0||row>=maze.length||col<0||col>=maze.length||visited[row][col]||maze[row][col]==0){
return;
}
visited[row][col]=true;
//Down
RatMaze(maze,visited,row+1,col,ans+"D",list);
//left
RatMaze(maze,visited,row,col-1,ans+"L",list);
//right
RatMaze(maze,visited,row,col+1,ans+"R",list);
//Up
RatMaze(maze,visited,row-1,col,ans+"U",list);
visited[row][col]=false;
}
-> to shorten the code
String dir = "DLRU";
for(int ind = 0; ind<4;ind++) {
int nexti = i + di[ind];
int nextj = j + dj[ind];
if(nexti >= 0 && nextj >= 0 && nexti < n && nextj < n
&& vis[nexti][nextj] == 0 && a[nexti][nextj] == 1) {
vis[i][j] = 1;
solve(nexti, nextj, a, n, ans, move + dir.charAt(ind), vis, di, dj);
vis[i][j] = 0;
}
}
where di[]={1,0,0,-1}, dj[]={0,-1,1,0}
------------------------------------------------------------------------------------------
2. N Queens
static int c5 = 1;
public static void NQueens(boolean[][] board, int qpsf, int tq, String ans, int row, int col) {
if (qpsf == tq) {
System.out.println(c5 + ") " + ans);
c5++;
return;
}
if (col == board[0].length) {
col = 0;
row++;
}
if (row == board.length) {
return;
}
// placed
if (isitsafetoplace(board, row, col)) {
board[row][col] = true;
NQueens(board, qpsf + 1, tq, ans + "{" + (row + 1) + "-" + (col + 1) + "} ", row, col + 1);
board[row][col] = false;
}
// not placed
NQueens(board, qpsf, tq, ans, row, col + 1);
}
private static boolean isitsafetoplace(boolean[][] board, int row, int col) {
// vertically up
int r = row - 1;
int c = col;
while (r >= 0) {
if (board[r][c]) {
return false;
}
r--;
}
// horizontally left
r = row;
c = col - 1;
while (c >= 0) {
if (board[r][c]) {
return false;
}
c--;
}
// diagonally left
r = row - 1;
c = col - 1;
while (r >= 0 && c >= 0) {
if (board[r][c]) {
return false;
}
r--;
c--;
}
// diagonally right
r = row - 1;
c = col + 1;
while (r >= 0 && c < board[0].length) {
if (board[r][c]) {
return false;
}
r--;
c++;
}
return true;
}
-> Optimised
public List<List<String>> solveNQueens(int n) {
char[][]board=new char[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
board[i][j]='.';
}
}
List<List<String>>res=new ArrayList<>();
//taking these arrays for quickly checking the safe cell (hashing concept)
int[]leftRow=new int[n];
int[]upperD=new int[2*n-1]; //upper left diagonal
int[]lowerD=new int[2*n-1]; //lower left diagonal
NQueens(0,n,board,leftRow,upperD,lowerD,res);
return res;
}
public void NQueens(int col,int n,char[][]board,int[]lr,int[]ud,int[]ld,List<List<String>>res){
if(col==n){
res.add(construct(board));
}
//at each column we searching for row to place the queen
for(int row=0;row<n;row++){
if(lr[row]==0 && ld[row+col]==0 && ud[(n-1)+(col-row)]==0){
board[row][col]='Q';
lr[row]=1;
ld[row+col]=1;
ud[(n-1)+(col-row)]=1;
NQueens(col+1,n,board,lr,ud,ld,res);
lr[row]=0;
ld[row+col]=0;
ud[(n-1)+(col-row)]=0;
board[row][col]='.';
}
}
}
public List<String> construct(char[][]board){
List<String>list=new ArrayList<>();
for(int i=0;i<board.length;i++){
String str = new String(board[i]);
list.add(str);
}
return list;
}
--------------------------------------------------------------------------------------------
3. Sudoku Solver
public static void Sudokusolver(int[][] arr, int row, int col) {
if (col == arr[0].length) {
col = 0;
row++;
}
if (row == arr.length) {
display(arr);
return;
}
if (arr[row][col] != 0) {
Sudokusolver(arr, row, col + 1);
return;
}
for (int i = 1; i <= 9; i++) {
if (isitsafe(arr, row, col, i)) {
arr[row][col] = i;
Sudokusolver(arr, row, col + 1);
arr[row][col] = 0;
}
}
}
private static boolean isitsafe(int[][] arr, int row, int col, int val) {
return isitsaferow(arr, row, val) && isitsafecol(arr, col, val) && isitsafecell(arr, row, col, val);
}
private static boolean isitsafecell(int[][] arr, int row, int col, int val) {
int sr = row - row % 3;
int sc = col - col % 3;
for (int r = sr; r < sr + 3; r++) {
for (int c = sc; c < sc + 3; c++) {
if (arr[r][c] == val) {
return false;
}
}
}
return true;
}
private static boolean isitsafecol(int[][] arr, int col, int val) {
for (int row = 0; row < arr.length; row++) {
if (arr[row][col] == val) {
return false;
}
}
return true;
}
private static boolean isitsaferow(int[][] arr, int row, int val) {
for (int col = 0; col < arr[0].length; col++) {
if (arr[row][col] == val) {
return false;
}
}
return true;
}
-> striver's solution
public void solveSudoku(char[][] board) {
if(board == null || board.length == 0)
return;
solve(board);
}
public boolean solve(char[][] board){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j] == '.'){
for(char c = '1'; c <= '9'; c++){//trial. Try 1 through 9
if(isValid(board, i, j, c)){
board[i][j] = c; //Put c for this cell
if(solve(board))
return true; //If it's the solution return true
else
board[i][j] = '.'; //Otherwise go back
}
}
return false;
}
}
}
return true;
}
private boolean isValid(char[][] board, int row, int col, char c){
for(int i = 0; i < 9; i++) {
if(board[i][col] != '.' && board[i][col] == c) return false; //check row
if(board[row][i] != '.' && board[row][i] == c) return false; //check column
if(board[3 * (row / 3) + i / 3][ 3 * (col / 3) + i % 3] != '.' &&
board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; //check 3*3 block
}
return true;
}
--------------------------------------------------------------------------------------------
4. Permutations of a string
public List<String> find_permutation(String S) {
List<String>list=new ArrayList<>();
HashMap<Character,Integer>map=new HashMap<>();
for(int i=0;i<S.length();i++){
char ch=S.charAt(i);
map.put(ch,map.getOrDefault(ch,0)+1);
}
Solve(map,list,1,S.length(),"");
Collections.sort(list);
return list;
}
public void Solve(HashMap<Character,Integer>map,List<String>list,int cs,int ts,String ans){
if(cs>ts){
list.add(ans);
return;
}
for(char key:map.keySet()){
if(map.get(key)>0){
map.put(key,map.get(key)-1);
Solve(map,list,cs+1,ts,ans+key);
map.put(key,map.get(key)+1);
}
}
}
--------------------------------------------------------------------------------------------
5. Knights Tour
public static boolean KnightsMove(int[][] chessboard, int row, int col, boolean[][] visited, int count) {
if (count == 8 * 8) {
display(chessboard);
return true;
}
if (row < 0 || row >= chessboard.length || col < 0 || col >= chessboard.length || visited[row][col]) {
return false;
}
visited[row][col] = true;
chessboard[row][col] = count;
if (KnightsMove(chessboard, row + 2, col + 1, visited, count + 1))
return true;
if (KnightsMove(chessboard, row + 1, col + 2, visited, count + 1))
return true;
if (KnightsMove(chessboard, row - 1, col + 2, visited, count + 1))
return true;
if (KnightsMove(chessboard, row - 2, col + 1, visited, count + 1))
return true;
if (KnightsMove(chessboard, row - 2, col - 1, visited, count + 1))
return true;
if (KnightsMove(chessboard, row - 1, col - 2, visited, count + 1))
return true;
if (KnightsMove(chessboard, row + 1, col - 2, visited, count + 1))
return true;
if (KnightsMove(chessboard, row + 2, col - 1, visited, count + 1))
return true;
chessboard[row][col] = 0;
visited[row][col] = false;
return false;
}
--------------------------------------------------------------------------------------------
6. Combination Sum
//Function to return a list of indexes denoting the required
// UNIQUE combinations whose sum is equal to given number.
public static ArrayList<ArrayList<Integer>> combinationSum(ArrayList<Integer> A, int B)
{
ArrayList<ArrayList<Integer>>ans=new ArrayList<>();
ArrayList<Integer>list=new ArrayList<>();
Set<Integer> set = new HashSet<>(A);
A.clear();
A.addAll(set);
Collections.sort(A);
int[]arr=new int[A.size()];
for(int i=0;i<arr.length;i++){
arr[i]=A.get(i);
}
CoinChange(B,0,ans,list,arr);
return ans;
}
public static void CoinChange(int amt,int lastcoinused,ArrayList<ArrayList<Integer>>ans,ArrayList<Integer>list,int[]arr){
if(amt==0){
ans.add(new ArrayList<>(list));
return;
}
for(int i=lastcoinused;i<arr.length;i++){
if(amt-arr[i]>=0){
amt=amt-arr[i];
list.add(arr[i]);
CoinChange(amt,i,ans,list,arr);
list.remove(list.size()-1);
amt=amt+arr[i];
}
}
}
--------------------------------------------------------------------------------------------
7. Print all Palindromic Partitions of a String
public static void PalindromicPartitions(String q, String ans) {
if (q.length() == 0) {
System.out.println(ans);
return;
}
for (int i = 1; i <= q.length(); i++) {
String part = q.substring(0, i);
String roq = q.substring(i);
if (ispalindrome(part)) {
PalindromicPartitions(roq, ans + part + " ");
}
}
}
--------------------------------------------------------------------------------------------
8. Maximum Integer with Atmost K Swaps
public static int MaximumIntegerWithAtMostKSwaps(char[] ch, int vidx, int k) {
int max = Integer.parseInt(new String(ch));
if (k == 0) {
return max;
}
for (int i = vidx; i < ch.length; i++) {
for (int j = i + 1; j < ch.length; j++) {
if (ch[j] > ch[i]) {
Swapping(ch, i, j);
int ans = MaximumIntegerWithAtMostKSwaps(ch, vidx + 1, k - 1);
max = Math.max(max, ans);
Swapping(ch, i, j);
}
}
}
return max;
}
--------------------------------------------------------------------------------------------
9. Work Break
static List<String> wordBreak(int n, List<String> dict, String s)
{
HashSet<String>set=new HashSet<>();
for(int i=0;i<dict.size();i++){
set.add(dict.get(i));
}
List<String>list=new ArrayList<>();
solve(set,list,"",s);
return list;
}
public static void solve(HashSet<String>set,List<String>list,String ans,String str){
if(str.length()==0){
list.add(ans.substring(0,ans.length()-1));
return;
}
for(int i=0;i<str.length();i++){
String left=str.substring(0,i+1);
String right=str.substring(i+1);
if(set.contains(left)){
solve(set,list,ans+left+" ",right);
}
}
}
Word Break II (LC-140)
public List<String> wordBreak(String s, List<String> wordDict) {
List<String>ans = new ArrayList<>();
WordBreak(s,wordDict,0,"",ans);
return ans;
}
public void WordBreak(String str,List<String>set,int start,String res,List<String>ans){
if(start>=str.length()){
ans.add(res.substring(0,res.length()-1));
return;
}
for(int end=start+1;end<=str.length();end++){
String s = str.substring(start,end);
if(set.contains(s)){
WordBreak(str,set,end,res+s+" ",ans);
}
}
}
--------------------------------------------------------------------------------------------
10. Partition in K subsets (non empty)-> pepcoding->https://www.youtube.com/watch?v=TvvGj1FtHIk&t=6s
Approach-> can we take a (existing non empty set) +(new set /(first non occupy set)) <- two options
at last at the end of tree all those which are not having a single empty set are the answers
Insights: if n-1 persons make k teams then nth person can go in any team.
but if n-1 persons were able to make k-1 teams then nth person should make kth team
public static void PartitionInKsubsets(int i, int n, int k, int nos, ArrayList<ArrayList<Integer>> ans) {
// nos->filled sets which were 0 initially
if (i > n) {
if (nos == k) {
for (ArrayList<Integer> set : ans) {
System.out.print(set + " ");
}
System.out.println();
}
return;
}
//Size of ans ArrayList is K.
for (int j = 0; j < ans.size(); j++) {
if (ans.get(j).size() > 0) {
// existing non empty set-> so "nos" will not increase
ans.get(j).add(i);
PartitionInKsubsets(i + 1, n, k, nos, ans);
ans.get(j).remove(ans.get(j).size() - 1);
} else {
// first non occupy set
ans.get(j).add(i);
PartitionInKsubsets(i + 1, n, k, nos + 1, ans);
ans.get(j).remove(ans.get(j).size() - 1);
break;// to prevent duplicacy
}
}
}
--------------------------------------------------------------------------------------------
11. Equal Sum subsets partition(k)
-> O(k*2^n)
public static void main(String[] args) throws java.lang.Exception {
int n = scn.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < arr.length; i++) {
arr[i] = scn.nextInt();
sum += arr[i];
}
Arrays.sort(arr);
int k = scn.nextInt();
if (k == 1) {
System.out.println("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ", ");
}
System.out.println("]");
return;
}
if (k > n || sum % k != 0) {
System.out.println("-1");
return;
}
int[] subsetSum = new int[k];
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
for (int i = 0; i < k; i++) {
ans.add(new ArrayList<>());
}
EqualSumSubsetPartition(arr, 0, k, 0, subsetSum, ans);
}
public static void EqualSumSubsetPartition(int[] arr, int vidx, int k, int nos, int[] subsetSum,
ArrayList<ArrayList<Integer>> ans) {
// nos->filled sets which were 0 initially
if (vidx == arr.length) {
if (nos == k) {
boolean flag = true;
for (int i = 0; i < subsetSum.length - 1; i++) {
if (subsetSum[i] != subsetSum[i + 1]) {
flag = false;
break;
}
}
if (flag) {
for (ArrayList<Integer> set : ans) {
System.out.print(set + " ");
}
System.out.println();
}
}
return;
}
for (int j = 0; j < ans.size(); j++) {
if (ans.get(j).size() > 0) {
// existing non empty set-> so "nos" will not increase
ans.get(j).add(arr[vidx]);
subsetSum[j] += arr[vidx];
EqualSumSubsetPartition(arr, vidx + 1, k, nos, subsetSum, ans);
subsetSum[j] -= arr[vidx];
ans.get(j).remove(ans.get(j).size() - 1);
} else {
// first non occupy set
ans.get(j).add(arr[vidx]);
subsetSum[j] += arr[vidx];
EqualSumSubsetPartition(arr, vidx + 1, k, nos + 1, subsetSum, ans);
subsetSum[j] -= arr[vidx];
ans.get(j).remove(ans.get(j).size() - 1);
break;// to prevent duplicacy
}
}
}
-> Easy Method
public boolean canPartitionKSubsets(int[] nums, int k) {
int total = 0;
for(int el: nums){
total+=el;
}
if(total%k !=0){
return false;
}
if (nums.length < k) return false;
int subsetSum = total/k;
boolean[] visited = new boolean[nums.length];
return canPartition(nums, visited, 0, k, 0, subsetSum);
}
private boolean canPartition(int[] nums, boolean[] visited, int start, int k, int curSum, int subsetSum) {
if (k == 0) return true;
if (curSum > subsetSum) return false;
if (curSum == subsetSum) {
return canPartition(nums, visited, 0, k - 1, 0, subsetSum);
}
for (int i = start; i < nums.length; i++) {
if (visited[i]) continue;
visited[i] = true;
if (canPartition(nums, visited, i + 1, k, curSum + nums[i], subsetSum)) return true;
visited[i] = false;
}
return false;
}
M2) Using BitMask
->
--------------------------------------------------------------------------------------------
12. Remove Invalid Parentheses->(Leetcode 301)
Intuition-> We remove every single parenthesis then check is it valid if valid then add it into ans
List<String>ans=new ArrayList<>();
Set<String>setA= new HashSet<>(); //this set is for checking if this some type of parenthesis have been called earlier.
public List<String> removeInvalidParentheses(String s) {
int mra=getMinRemovals(s);
//minimum removals allowed
Set<String>set=new HashSet<>(); //this set is for storing the valid parenthesis.
solution(mra,set,s);
return ans;
}
public void solution(int mra,Set<String>set,String str){
if(mra==0){
int mr=getMinRemovals(str);
if(mr==0){//minimum removals ==0 means stack is empty means valid parentheses
if(!set.contains(str)){
set.add(str);
ans.add(str);
}
}
return;
}
for(int i=0;i<str.length();i++){
String left=str.substring(0,i);
String right=str.substring(i+1); //here we remove every element and check for validity
if(!setA.contains(left+right)){
setA.add(left+right);
solution(mra-1,set,left+right);
}
}
}
public int getMinRemovals(String str){
Stack<Character>st=new Stack<>();
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if(ch=='('){
st.push(ch);
}else if(ch==')'){
if(!st.isEmpty() && st.peek()=='('){
st.pop();
}else{
st.push(ch);
}
}
}
return st.size();
}
--------------------------------------------------------------------------------------------
13. Tug Of War-(Minimum subset sum difference)
static int mindiff = Integer.MAX_VALUE;
static String ans = "";
private static void TugOfWar(int[] arr, int vidx, int sos1, int sos2, ArrayList<Integer> set1,
ArrayList<Integer> set2) {
if (vidx == arr.length) {
int delta = Math.abs(sos1 - sos2);
if (mindiff > delta) {
mindiff = delta;
ans = set1 + " " + set2;
}
return;
}
// this handles both even and odd cases.
if (set1.size() < (arr.length + 1) / 2) {
set1.add(arr[vidx]);
TugOfWar(arr, vidx + 1, sos1 + arr[vidx], sos2, set1, set2);
set1.remove(set1.size() - 1);
}
if (set2.size() < (arr.length + 1) / 2) {
set2.add(arr[vidx]);
TugOfWar(arr, vidx + 1, sos1, sos2 + arr[vidx], set1, set2);
set2.remove(set2.size() - 1);
}
}
Striver Approach - >
public static int minSubsetSumDifference(int[] arr, int n) {
int tar = 0;
for(int num:arr){
tar+=num;
}
boolean[][]dp = new boolean[n][tar+1];
//adding base cases
for(int i=0;i<n;i++){
dp[i][0]=true;
}
if(arr[0]<=tar){
dp[0][arr[0]]=true;
}
for(int i=1;i<n;i++){
for(int j=1;j<=tar;j++){
boolean take = false;
if(j>=arr[i]){
take = dp[i-1][j-arr[i]];
}
boolean noTake = dp[i-1][j];
dp[i][j] = (take || noTake);
}
}
// here are basically checking all the valid targets which can be achived with the all the elements of the array.
// and if its valid then check the sum at which its valid, and then find the another subset so that both sum makes the total sum of the array. and then for each valid case check the absolute minDiff.
int minDiff = Integer.MAX_VALUE;
for(int i=0;i<=tar/2;i++){
if(dp[n-1][i]){
int s1 = i;
int s2 = tar-s1;
minDiff=Math.min(minDiff,Math.abs(s1-s2));
}
}
return minDiff;
}
--------------------------------------------------------------------------------------------
14. Longest Possible Route in a Matrix with Hurdles
static int maxdis = Integer.MIN_VALUE;
private static void LongestPossiblePathInMatrix(int[][] mat, boolean[][] visited, int cr, int cc, int er, int ec,
int dis) {
if (cr == er && cc == ec) {
maxdis = Math.max(maxdis, dis);
return;
}
visited[cr][cc] = true;
if (isValid(mat, visited, cr - 1, cc))
LongestPossiblePathInMatrix(mat, visited, cr - 1, cc, er, ec, dis + 1);
if (isValid(mat, visited, cr, cc + 1))
LongestPossiblePathInMatrix(mat, visited, cr, cc + 1, er, ec, dis + 1);
if (isValid(mat, visited, cr + 1, cc))
LongestPossiblePathInMatrix(mat, visited, cr + 1, cc, er, ec, dis + 1);
if (isValid(mat, visited, cr, cc - 1))
LongestPossiblePathInMatrix(mat, visited, cr, cc - 1, er, ec, dis + 1);
visited[cr][cc] = false;
}
private static boolean isValid(int[][] mat, boolean[][] visited, int row, int col) {
if (row >= 0 && col >= 0 && row < mat.length && col < mat[0].length && mat[row][col] == 1
&& !visited[row][col]) {
return true;
}
return false;
}
--------------------------------------------------------------------------------------------
15.Print all possible paths from top left to bottom right of a mXn matrix
private static void MatrixTraversal(int[][] mat, int r, int c, int m, int n, String ans) {
if (r == m - 1 && c == n - 1) {
System.out.println(ans + mat[r][c]);
return;
}
if (r > m - 1 || c > n - 1) {
return;
}
MatrixTraversal(mat, r + 1, c, m, n, ans + mat[r][c] + " ");
MatrixTraversal(mat, r, c + 1, m, n, ans + mat[r][c] + " ");
}
--------------------------------------------------------------------------------------------
16. K-th Permutation Sequence->https://www.youtube.com/watch?v=wT7gcXLYoao
Approach-> suppose number is n= 4 ->arr[]={1,2,3,4} and k=17-1=16 (0th based indexing)
here now 4! gives 24 permutations out of which we need 17th so here if
1 +{[2,3,4] => 6}
2+{[1,3,4] =>6}
3+{[1,2,4] =>6}
4+{[1,2,3] =>6} Each part contains 6 permutations if one number is separated now out of this we can find the first number for our kth(16th) permutation using (k/6)means k/(n-1)! =(16/6)gives "2" which is number "3" in 0th based array. and in this , for the first number as 3 we have to find the permutation of (16%6)=4th permutation of the remaining arraylist/array=[1,2,4].
Here our k changed to 4, and fact changes to (6/size) of arraylist which is "2".
1 +{[2,4]=>2}
2+{[1,4]=>2}
4+{[1,2]=>2} Now again here we find (k/fact)th term in arraylist which is (4/2)=2 which "4" in 0th based arraylist.
so the second number is definitely 4 and now in this four we have to find the 4%2=0th permutation and so on...
Ans= "3412"
public String getPermutation(int n, int k) {
int fact=1;
List<Integer>list=new ArrayList<>();
for(int i=1;i<n;i++){
list.add(i);
fact=fact*i;
}
list.add(n);
k=k-1;//0th based indexing
String ans="";
while(true){
ans=ans+list.get(k/fact);
list.remove(k/fact);
if(list.size()==0){
break;
}
k=k%fact;
fact=fact/list.size();
}
return ans;
}
--------------------------------------------------------------------------------------------
17. Letter Combinations of a phone number (LC-17)
-> public List<String> letterCombinations(String digits) {
if(digits.length()==0)return new ArrayList<>();
List<String>ans = new ArrayList<>();
letterCombinations(digits.toCharArray(),0,"",ans);
return ans;
}
public void letterCombinations(char[]digits,int idx,String s,List<String>ans){
if(idx==digits.length){
ans.add(s);
return;
}
char[]crr = getCode(digits[idx]);
for(int i=0;i<crr.length;i++){
letterCombinations(digits,idx+1,s+crr[i],ans);
}
}
public char[] getCode(char ch){
switch (ch) {
case '2' : return new char[] {'a','b','c'};
case '3' : return new char[] {'d','e','f'};
case '4' : return new char[] {'g','h','i'};
case '5' : return new char[] {'j','k','l'};
case '6' : return new char[] {'m','n','o'};
case '7' : return new char[] {'p','q','r','s'};
case '8' : return new char[] {'t','u','v'};
case '9' : return new char[] {'w','x','y','z'};
}
return null;
}
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------