Repository navigation
Expand file tree
/
Copy pathGraphs.cpp
More file actions
1581 lines (1263 loc) · 40.2 KB
/
Copy pathGraphs.cpp
File metadata and controls
1581 lines (1263 loc) · 40.2 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 <iostream>
#include <cmath>
#include <limits.h>
#include <vector>
#include <string>
#include <list>
#include <typeinfo>
#include <algorithm>
#include <iterator>
#include <utility>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
using namespace std;
// Graph Adjacency List
// Template, it will replace the given type with it, it only works for a block of code like class or function
template <typename T> class Graph {
public:
unordered_map<T, list<T>> adjList;
// ctor
Graph() {}
// dtor
~Graph() {}
// Add Edges, 0 undirected, 1 directed
void AddEdge(T u, T v, bool direction) {
// u -> v
if(direction) {
adjList[u].push_back(v);
}
// u -> v && v -> u
else {
adjList[u].push_back(v);
adjList[v].push_back(u);
}
}
// BFS
void bfsTraversal(T source) {
// Already visited nodes
unordered_map<T, bool> visited;
// Queue for maintaining nodes
queue<T> q;
// Initial State
q.push(source);
visited[source] = true;
while(!q.empty()) {
T frontNode = q.front();
cout<<frontNode<<' ';
q.pop();
// Neighbour pushing and marking it as true
for(auto neighbour: adjList[frontNode]) {
if(!visited[neighbour]) {
q.push(neighbour);
visited[neighbour] = true;
}
}
}
return;
}
// BFS for Disconnected graphs
// Adding visited in the by-reference part for disconnected part
void bfsTraversalDis(T source, unordered_map<T, bool> &visited) {
// Queue for maintaining nodes
queue<T> q;
// Initial State
q.push(source);
visited[source] = true;
while(!q.empty()) {
T frontNode = q.front();
cout<<frontNode<<' ';
q.pop();
// Neighbour pushing and marking it as true
for(auto neighbour: adjList[frontNode]) {
if(!visited[neighbour]) {
q.push(neighbour);
visited[neighbour] = true;
}
}
}
return;
}
// DFS
void dfsTraversal(T source, unordered_map<T, bool> &visited) {
// Base Case
if(visited[source]) {
return;
}
cout<<source<<' ';
visited[source] = true;
for(auto ch: adjList[source]) {
dfsTraversal(ch, visited);
}
return;
}
// Cycle Detection in undirected graph using BFS
bool CycleUndirectedBFS(int source, unordered_map<int, bool> &visited) {
queue<int> q;
// Parent Node
unordered_map<int, int> parent;
q.push(source);
visited[source] = true;
parent[source] = -1;
while(!q.empty()) {
int frontNode = q.front();
q.pop();
for(int nbr: adjList[frontNode]) {
if(!visited[nbr]) {
q.push(nbr);
visited[nbr] = true;
parent[nbr] = frontNode;
}
// 2nd Parent means cycle
else if(nbr != parent[frontNode]) {
return true;
}
}
}
// No cycle detected
return false;
}
// Cycle Detection in undirected graph using DFS
bool CycleUndirectedDFS(int source, int parent, unordered_map<int, bool> &visited) {
visited[source] = true;
for(int nbr: adjList[source]) {
if(!visited[nbr]) {
if(CycleUndirectedDFS(nbr, source, visited)) {
return true;
}
}
// Visited condition removed, if not visited it will go to if condition
// nbrs me new element ya parent(2 way relation) hoga, visited hai parent nai hai matlab cycle hai
else if(nbr != parent) {
return true;
}
}
return false;
}
// Cycle Detection in directed graph using DFS
// Self 5->5 is satisfied
bool CycleDirectedDFS(int source, unordered_map<int, bool> &visited, unordered_map<int, bool> &dfsTrack) {
visited[source] = true;
dfsTrack[source] = true;
for(int nbr: adjList[source]) {
if(!visited[nbr]) {
if(CycleDirectedDFS(nbr, visited, dfsTrack)) {
return true;
}
}
else if(visited[nbr] && dfsTrack[nbr]) {
return true;
}
}
// BackTrack, main source wouldnt be checked as it has gone through loop
// 3->0, 4->2, 1->2
// 2 would be backtracked in case of 4 and could be checked for 1 again
dfsTrack[source] = false;
return false;
}
// Topological Sort using DFS
void TopoSortDFS(int source, unordered_map<int, bool> &visited, stack<int> &st) {
visited[source] = true;
for(int nbr: adjList[source]) {
if(!visited[nbr]) {
TopoSortDFS(nbr, visited, st);
}
}
st.push(source);
return;
}
// Topological Sort using BFS, Kahn's Algorithm
void TopoSortBFS(int n, vector<int> &topoSorted) {
queue<int> q;
unordered_map<int, int> inDegree;
// Using whole adjList, bakiyo ki inDegree bhi 0 krni padegi, disconnected me unke wale elements ki inDegree bhi mark hori
for(auto i: adjList) {
// List checking
for(int ch: i.second) {
inDegree[ch]++;
}
}
// Pushing all elements with inDegree 0
for(int i=0; i<n; i++) {
if(inDegree[i] == 0) {
q.push(i);
}
}
while(!q.empty()) {
int frontNode = q.front();
q.pop();
topoSorted.push_back(frontNode);
// Poped element ki inDegree--
for(int ch: adjList[frontNode]) {
inDegree[ch]--;
// inDegree 0 ho jae toh push in queue
if(inDegree[ch] == 0) {
q.push(ch);
}
}
}
return;
}
// Cycle Detection in directed graph using BFS and Topology Sort
bool CycleDirectedBFS(int n, vector<int> &topoSorted) {
TopoSortBFS(n, topoSorted);
// Cycle made inDegree != 0, so not pushed in queue
if(topoSorted.size() != n) {
return true;
}
return false;
}
// Shortest Path BFS in undirected graph, disconnected when if(node == source toh call krdo iss function ko)
vector<int> ShortestPathUndirBFS(int source, int target) {
queue<int> q;
unordered_map<int, int> parent;
unordered_map<int, bool> visited;
bool targetFound = false;
vector<int> shortestPath;
q.push(source);
parent[source] = -1;
visited[source] = true;
while(!q.empty()) {
int frontNode = q.front();
q.pop();
for(int nbr: adjList[frontNode]) {
if(!visited[nbr]) {
visited[nbr] = true;
parent[nbr] = frontNode;
if(nbr == target) {
targetFound = true;
break;
}
q.push(nbr);
}
}
if(targetFound) {
break;
}
}
// If target is found, otherwise return empty array
if(targetFound) {
int curr = target;
while(curr != -1) {
shortestPath.push_back(curr);
curr = parent[curr];
}
// In alogirthm STL
reverse(shortestPath.begin(), shortestPath.end());
}
return shortestPath;
}
void sccDFSTraversal(int source, unordered_map<int, bool> &newVisited, unordered_map<int, list<int>> &adjNew) {
// Base Case
if(newVisited[source]) {
return;
}
newVisited[source] = true;
for(auto ch: adjNew[source]) {
sccDFSTraversal(ch, newVisited, adjNew);
}
return;
}
// Strongly Connected Component, Kosaraju Algorithm, DFS because it will give all dependencies
int StronglyConnectedComponent(int n) {
int count = 0;
stack<int> st;
unordered_map<int, bool> visited;
// Reverse Finishing Time Ordering, stack me finish hone ka time, just like TopoSort
for(int i=0; i<n; i++) {
if(!visited[i]) {
TopoSortDFS(i, visited, st);
}
}
// Reverse the order
unordered_map<int, list<int>> adjNew;
for(auto nbrList: adjList) {
int v = nbrList.first;
for(int u: nbrList.second) {
adjNew[u].push_back(v);
}
}
unordered_map<int, bool> newVisited;
while(!st.empty()) {
int node = st.top();
st.pop();
if(!newVisited[node]) {
count++;
sccDFSTraversal(node, newVisited, adjNew);
}
}
return count;
}
};
// Weighted Graph Adjacency List
template <typename T> class Wgraph {
public:
// Pair is v and weight
unordered_map<T, list<pair<T, T>>> adjList;
// ctor
Wgraph() {}
// dtor
~Wgraph() {}
// Add Edges, 0 undirected, 1 directed
void AddEdge(T u, T v, int weight, T direction) {
// u -> v
if(direction) {
adjList[u].push_back( {v, weight} );
}
// u -> v && v -> u
else {
adjList[u].push_back( {v, weight} );
adjList[v].push_back( {u, weight}) ;
}
}
// BFS
void bfsTraversal(T source) {
// Already visited nodes
unordered_map<T, bool> visited;
// Queue for maintaining nodes
queue<T> q;
// Initial State
q.push(source);
visited[source] = true;
while(!q.empty()) {
T frontNode = q.front();
cout<<frontNode<<' ';
q.pop();
// Neighbour pushing and marking it as true
for(auto neighbour: adjList[frontNode]) {
T neighbourData = neighbour.first;
if(!visited[neighbourData]) {
q.push(neighbourData);
visited[neighbourData] = true;
}
}
}
return;
}
// BFS for Disconnected graphs
// Adding visited in the by-reference part for disconnected part
void bfsTraversalDis(T source, unordered_map<T, bool> &visited) {
// Queue for maintaining nodes
queue<T> q;
// Initial State
q.push(source);
visited[source] = true;
while(!q.empty()) {
T frontNode = q.front();
cout<<frontNode<<' ';
q.pop();
// Neighbour pushing and marking it as true
for(auto neighbour: adjList[frontNode]) {
T neighbourData = neighbour.first;
if(!visited[neighbourData]) {
q.push(neighbourData);
visited[neighbourData] = true;
}
}
}
return;
}
// DFS
void dfsTraversal(T source, unordered_map<T, bool> &visited) {
// Base Case
if(visited[source]) {
return;
}
cout<<source<<' ';
visited[source] = true;
for(auto ch: adjList[source]) {
dfsTraversal(ch.first, visited);
}
return;
}
// Topological Sort Using DFS
void TopoSortDFS(int source, unordered_map<int, bool> &visited, stack<int> &st) {
visited[source] = true;
for(auto nbr: adjList[source]) {
if(!visited[nbr.first]) {
TopoSortDFS(nbr.first, visited, st);
}
}
st.push(source);
return;
}
// Topological Sort using BFS
void TopoSortBFS(int n, vector<int> &topoSorted) {
unordered_map<int, bool> visited;
unordered_map<int, int> inDegree;
queue<int> q;
for(auto i: adjList) {
for(auto ch: i.second) {
inDegree[ch.first]++;
}
}
for(int i=0; i<n; i++) {
if(inDegree[i] == 0) {
q.push(i);
}
}
while(!q.empty()) {
int frontNode = q.front();
q.pop();
topoSorted.push_back(frontNode);
for(auto nbr: adjList[frontNode]) {
inDegree[nbr.first]--;
if(inDegree[nbr.first] == 0) {
q.push(nbr.first);
}
}
}
return;
}
// Shortest Path DFS in directed graph using TopoSort and visited
// Disconnected when if(node == source toh call krdo iss function ko
// n isliye kyuki vector, initialise krna hai
void ShortestPathDirDFS(int n, stack<int> &topoOrder) {
vector<int> distance(n, INT_MAX);
// Source determining
int source = topoOrder.top();
topoOrder.pop();
// Setting source distance
distance[source] = 0;
for(auto nbrPair: adjList[source]) {
int nbrNode = nbrPair.first;
int nbrDistance = nbrPair.second;
// Placing shorter distance in distance array, updation
if(distance[source] + nbrDistance < distance[nbrNode]) {
distance[nbrNode] = distance[source] + nbrDistance;
}
}
// Until distance for everynode is checked
while(!topoOrder.empty()) {
source = topoOrder.top();
topoOrder.pop();
for(auto nbrPair: adjList[source]) {
int nbrNode = nbrPair.first;
int nbrDistance = nbrPair.second;
// Placing shorter distance in distance array, updation
if(distance[source] + nbrDistance < distance[nbrNode]) {
distance[nbrNode] = distance[source] + nbrDistance;
}
}
}
cout<<"Shortest distances are:"<<endl;
for(int ch: distance) {
cout<<ch<<' ';
}
cout<<endl;
return;
}
// Dijkstra Algorithm, doesnt work on unreachable nodes & negative cycle
int DijkstraAlgorithm(int n, int source, int destination) {
vector<int> distance(n, INT_MAX);
set<pair<int, int>> DistAndNode;
// Initial State
distance[source] = 0;
DistAndNode.insert( {distance[source], source} );
// Distance Updation Logic
while(!DistAndNode.empty()) {
pair<int, int> topPair = *DistAndNode.begin();
int topNode = topPair.second;
int topDist = topPair.first;
// Iterator deletion is faster
DistAndNode.erase(DistAndNode.begin());
for(auto nbr: adjList[topPair.second]) {
int nbrNode = nbr.first;
int nbrDist = nbr.second;
// Updation
if(topDist + nbrDist < distance[nbrNode]) {
auto it = DistAndNode.find( {distance[nbrNode], nbrNode} );
if(it != DistAndNode.end()) {
DistAndNode.erase(it);
}
distance[nbrNode] = topDist + nbrDist;
DistAndNode.insert( {distance[nbrNode], nbrNode} );
}
}
}
return distance[destination];
}
// Bellman-Ford Algorithm, doesnt work on unreachable nodes & negative cycle, but can detect negative cycles
int BellmanFordAlgorithm(int n, int source, int destination) {
vector<int> distance(n, INT_MAX);
distance[source] = 0;
for(int i=1; i<n; i++) {
bool distChanged = false;
for(auto nbrList: adjList) {
for(auto nbr: nbrList.second) {
// From nbrList
int u = nbrList.first;
// nbr
int v = nbr.first;
int wt = nbr.second;
// Starting me sab int max rahega then INT_MAX + wt overflow ho jaega
if(distance[u] != INT_MAX && distance[v] > distance[u] + wt) {
distChanged = true;
distance[v] = distance[u] + wt;
}
}
}
if(!distChanged) {
break;
}
}
// Negative Cycle
bool distChanged = false;
for(auto nbrList: adjList) {
for(auto nbr: nbrList.second) {
// From nbrList
int u = nbrList.first;
// nbr
int v = nbr.first;
int wt = nbr.second;
// Starting me sab int max rahega then INT_MAX + wt overflow ho jaega
if(distance[u] != INT_MAX && distance[v] > distance[u] + wt) {
distChanged = true;
distance[v] = distance[u] + wt;
}
}
}
if(distChanged) {
cout<<"Negative Cycle Detected"<<endl;
return -1;
}
return distance[destination];
}
// Floyd Warshall Algorithm, DP, doesnt work on unreachable nodes & negative cycle
vector<vector<int>> FloydWarshallAlgorithm(int n) {
vector<vector<int>> distance(n, vector<int>(n, 1e9));
// Diagonals will be zero
for(int i=0; i<n; i++) {
distance[i][i] = 0;
}
// Initial weights to go from one node to other
for(auto nbrList: adjList) {
for(auto nbr: nbrList.second) {
int u = nbrList.first;
int v = nbr.first;
int wt = nbr.second;
distance[u][v] = wt;
}
}
for(int helper=0; helper<n; helper++) {
for(int src=0; src<n; src++) {
for(int dest=0; dest<n; dest++) {
distance[src][dest] = min( distance[src][dest], (distance[src][helper] + distance[helper][dest]) );
}
}
}
return distance;
}
};
// L.C 207, Course Schedule, Graph, TopoSort & Cycle Detection
// Topological Sort using BFS
vector<int> CourseSchedule1TopoSortBFS(int n, unordered_map<int, list<int>> &adjList) {
unordered_map<int, int> inDegree;
queue<int> q;
vector<int> topoSorted;
// Calculating inDegree using overall adjList
for(auto i: adjList) {
for(int ch: i.second) {
inDegree[ch]++;
}
}
// Independent ans source nodes
for(int i=0; i<n; i++) {
if(inDegree[i] == 0) {
q.push(i);
}
}
while(!q.empty()) {
int frontNode = q.front();
q.pop();
topoSorted.push_back(frontNode);
for(int nbr: adjList[frontNode]) {
inDegree[nbr]--;
if(inDegree[nbr] == 0) {
q.push(nbr);
}
}
}
return topoSorted;
}
// Topological Sort Cycle Detection using DFS
bool CourseSchedule1CycleDirectedDFS(int source, unordered_map<int, list<int>> &adjList, unordered_map<int, bool> &visited, unordered_map<int, bool> &dfsTrack) {
visited[source] = true;
dfsTrack[source] = true;
for(int nbr: adjList[source]) {
// Base Case, when no more visit left
if(!visited[nbr]) {
// Recursive Call
bool ans = CourseSchedule1CycleDirectedDFS(nbr, adjList, visited, dfsTrack);
if(ans) {
return true;
}
}
// cycle Detected
else if(visited[nbr] && dfsTrack[nbr]) {
return true;
}
}
dfsTrack[source] = false;
return false;
}
bool CourseSchedule(int numCourses, vector<vector<int>> &prerequisites) {
unordered_map<int, list<int>> adjList;
// Directed Graph
for(vector<int> ch: prerequisites) {
adjList[ch[1]].push_back(ch[0]);
}
// BFS
// vector<int> topoSorted = CourseSchedule1TopoSortBFS(numCourses, adjList);
// if(topoSorted.size() == numCourses) {
// return true;
// }
// return false;
// DFS
unordered_map<int, bool> visited;
unordered_map<int, bool> dfsTrack;
for(int i=0; i<numCourses ; i++) {
if(!visited[i]) {
if(CourseSchedule1CycleDirectedDFS(i, adjList, visited, dfsTrack)) {
return false;
}
}
}
return true;
}
// L.C 210, Course Schedule II, Graph, TopoSort & Cycle Detection
// Topological Sort using BFS
vector<int> CourseSchedule2TopoSortBFS(int n, unordered_map<int, list<int>> &adjList) {
unordered_map<int, int> inDegree;
queue<int> q;
vector<int> topoSorted;
// Calculating inDegree using overall adjList
for(auto i: adjList) {
for(int ch: i.second) {
inDegree[ch]++;
}
}
// Independent ans source nodes
for(int i=0; i<n; i++) {
if(inDegree[i] == 0) {
q.push(i);
}
}
while(!q.empty()) {
int frontNode = q.front();
q.pop();
topoSorted.push_back(frontNode);
for(int nbr: adjList[frontNode]) {
inDegree[nbr]--;
if(inDegree[nbr] == 0) {
q.push(nbr);
}
}
}
return topoSorted;
}
// Topological Sort Cycle Detection using DFS
bool CourseSchedule2CycleDirectedDFS(int source, unordered_map<int, list<int>> &adjList, unordered_map<int, bool> &visited, unordered_map<int, bool> &dfsTrack, vector<int> &topoSorted) {
visited[source] = true;
dfsTrack[source] = true;
for(int nbr: adjList[source]) {
// Base Case, when no more visit left
if(!visited[nbr]) {
// Recursive Call
bool ans = CourseSchedule2CycleDirectedDFS(nbr, adjList, visited, dfsTrack, topoSorted);
if(ans) {
return true;
}
}
// cycle Detected
else if(visited[nbr] && dfsTrack[nbr]) {
return true;
}
}
topoSorted.push_back(source);
dfsTrack[source] = false;
return false;
}
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites) {
vector<int> topoSorted;
unordered_map<int, list<int>> adjList;
// Directed Graph
for(vector<int> ch: prerequisites) {
adjList[ch[1]].push_back(ch[0]);
}
// BFS
// topoSorted = CourseSchedule2TopoSortBFS(numCourses, adjList);
// if(numCourses != topoSorted.size()) {
// return {};
// }
// DFS
unordered_map<int, bool> visited;
unordered_map<int, bool> dfsTrack;
for(int i=0; i<numCourses ; i++) {
if(!visited[i]) {
if(CourseSchedule2CycleDirectedDFS(i, adjList, visited, dfsTrack, topoSorted)) {
return {};
}
}
}
// Reversing the array
reverse(topoSorted.begin(), topoSorted.end());
return topoSorted;
}
// L.C 1631, Path With Minimum Effort, Graph, Dijkstra
bool IsSafeMinimumEffortPath(int newX, int newY, int tRows, int tCols) {
if(newX < 0 || newY < 0 || newX >= tRows || newY >= tCols) {
return false;
}
return true;
}
int MinimumEffortPath(vector<vector<int>> &heights) {
int tRows = heights.size();
int tCols = heights[0].size();
vector<vector<int>> diff(tRows, vector<int>(tCols, INT_MAX));
// Distance, i, j
set<vector<int>> minSet;
diff[0][0] = 0;
minSet.insert( {0, 0, 0} );
while(!minSet.empty()) {
vector<int> top = *minSet.begin();
minSet.erase(minSet.begin());
int topDiff = top[0];
int topX = top[1];
int topY = top[2];
// All directiona
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
for(int i=0; i<4; i++) {
int newX = topX + dx[i];
int newY = topY + dy[i];
if(IsSafeMinimumEffortPath(newX, newY, tRows, tCols)) {
// Path's Max Diff from topDiff
int maxDiff = max(topDiff, abs(heights[topX][topY] - heights[newX][newY]) );
// Overall Min Diff to reach element
if(diff[newX][newY] > maxDiff) {
// Iterator make it easy in 1 search, otherwise first count then erase cost 2 searches
auto it = minSet.find( {diff[newX][newY], newX, newY} );
if(it != minSet.end()) {
minSet.erase(it);
}
// Updating minSet
diff[newX][newY] = maxDiff;
minSet.insert( {diff[newX][newY], newX, newY} );
}
}
}
}
return diff[tRows-1][tCols-1];
}
// L.C 547, Number of Provinces, Graph, No. of components
// BFS
void FindCircleNumBFS(int source, unordered_map<int, vector<int>> &adjList, unordered_map<int, bool> &visited) {
// Source
queue<int> q;
q.push(source);
visited[source] = true;
while(!q.empty()) {
int frontNode = q.front();
q.pop();
for(int nbr: adjList[frontNode]) {
if(!visited[nbr]) {
q.push(nbr);
visited[nbr] = true;
}
}
}
return;
}
// DFS
void FindCircleNumDFS(int source, unordered_map<int, vector<int>> &adjList, unordered_map<int, bool> &visited) {
visited[source] = true;
for(int nbr: adjList[source]) {
if(!visited[nbr]) {
FindCircleNumDFS(nbr, adjList, visited);
}
}
return;
}
int FindCircleNum(vector<vector<int>> &isConnected) {
int size = isConnected.size();
int count = 0;
// Undirected Graph
unordered_map<int, vector<int>> adjList;
unordered_map<int, bool> visited;
// AddEdge
for(int i=0; i<size; i++) {
for(int j=0; j<size; j++) {
if(isConnected[i][j]) {
adjList[i].push_back(j);
}
}
}
// Count number of disconnected components
for(int i=0; i<size; i++) {
if(!visited[i]) {
count++;
// BFS
// FindCircleNumBFS(i, adjList, visited);
// DFS
FindCircleNumDFS(i, adjList, visited);
}
}
return count;
}