├── .DS_Store ├── Graphs C++ ├── .DS_Store ├── 01 - Graph Representation │ ├── 01_adj_list.cpp │ ├── 02_adj_list.cpp │ └── 02_adj_list_node.cpp ├── 02 - Breadth First Search │ ├── 03_bfs_.cpp │ ├── 03_bfs_shortest_path.cpp │ └── sol_snakes_and_ladder.cpp ├── 03 - Depth First Search │ ├── 04_dfs.cpp │ ├── largest_island copy.cpp │ ├── largest_island.cpp │ └── sol_longest_path_sequence.cpp ├── 04 - Cycle Detection │ ├── .DS_Store │ ├── bipartitie.cpp │ ├── cycle_detection_directed.cpp │ └── cycle_detection_undirected.cpp ├── 05 - Directed Acyclic Graph │ ├── topological_bfs.cpp │ ├── topological_dfs.cpp │ └── topological_sort.cpp ├── 06 - Disjoint Set Union │ ├── dsu_1.cpp │ ├── dsu_2.cpp │ └── dsu_rank_path_compression.cpp ├── 07 - Minimum Spanning Trees │ ├── .DS_Store │ ├── kruskal_code.cpp │ └── prims_code.cpp ├── 08 - Shortest Path Algorithms │ ├── bellman_ford.cpp │ ├── dijkstra.cpp │ ├── floyd_warshall.cpp │ └── shortest_grid_path.cpp ├── 09 - Travelling Salesman Problem │ └── travelling_saleman.cpp ├── 10 - Flood Fill │ ├── Flood Fill Total connected Components.cpp │ ├── Flood Fill alphabet match.cpp │ ├── Flood Fill make largest island.cpp │ ├── Flood fill color count.cpp │ ├── flood fill largest island.cpp │ └── graph input.cpp ├── 11 - Multi Source BFS │ ├── Multi source BFS minimum operations .cpp │ ├── multisurce BFS (minimum distance).cpp │ └── shortest path from first row to last row.cpp ├── 12 - DFS Tree and Backedges │ ├── DFS tree and backedge code.cpp │ ├── DFS tree and backedges in Directed Graphs.cpp │ └── print cycle in a graph.cpp ├── 13 - Articulation Point and Bridges │ └── articulation point and bridges.cpp ├── 14 - Strongly Connected Components │ ├── kosaraju algorithm for SCC.cpp │ └── topological Order.cpp ├── 15 - Trees │ └── ancestor printing .cpp ├── 16 - Euler Tour │ ├── best euler tour.cpp │ └── euler tours.cpp ├── 17 - LCA │ ├── LCA using 2 pointers.cpp │ └── LCA using sparse table.cpp ├── 18 - Re rooting of. trees │ ├── Re-rooting brrute force.cpp │ └── re rooting .cpp ├── 19 - Network Flow │ └── dinic's algprithm.cpp └── 20 - Bonus │ └── board-game.cpp ├── Graphs Java ├── .DS_Store ├── .idea │ ├── .gitignore │ ├── kotlinc.xml │ ├── libraries │ │ └── KotlinJavaRuntime.xml │ ├── misc.xml │ ├── modules.xml │ └── uiDesigner.xml ├── Graphs.iml ├── out │ ├── .DS_Store │ └── production │ │ ├── .DS_Store │ │ └── Graphs │ │ ├── .DS_Store │ │ ├── ArticulationPointAndBridges │ │ ├── ArticulationPointAndBridges$Pair.class │ │ └── ArticulationPointAndBridges.class │ │ ├── Bonus │ │ ├── BoardGame$Node.class │ │ ├── BoardGame$Trie.class │ │ └── BoardGame.class │ │ ├── BreadthFirstSearch │ │ ├── Bfs$Graph.class │ │ ├── Bfs.class │ │ ├── BfsShortestPath$Graph.class │ │ ├── BfsShortestPath.class │ │ ├── Pair.class │ │ ├── snakesAndLadder$Graph.class │ │ └── snakesAndLadder.class │ │ ├── CycleDetection │ │ ├── Bipartite.class │ │ ├── CycleDetectionDirected$Graph.class │ │ ├── CycleDetectionDirected.class │ │ ├── CycleDetectionUndirected$Graph.class │ │ └── CycleDetectionUndirected.class │ │ ├── DepthFirstSearch │ │ ├── LongestPathSequence.class │ │ ├── dfs$Graph.class │ │ ├── dfs.class │ │ ├── largestIsland.class │ │ └── largestIslandCopy.class │ │ ├── DfsTreesAndBackEdges │ │ ├── CycleInGraph.class │ │ ├── DfsTreesAndBackEdges.class │ │ └── DfsTreesAndBackEdgesDirected.class │ │ ├── DirectedAcyclicGraph │ │ ├── topologicalBFS$Graph.class │ │ ├── topologicalBFS.class │ │ ├── topologicalDFS$Graph.class │ │ ├── topologicalDFS.class │ │ ├── topologicalSort$Graph.class │ │ └── topologicalSort.class │ │ ├── DisjointSetUnion │ │ ├── DSU_1$Graph.class │ │ ├── DSU_1$Pair.class │ │ ├── DSU_1.class │ │ ├── DSU_2$Graph.class │ │ ├── DSU_2$Pair.class │ │ ├── DSU_2.class │ │ ├── DSUrankPathCompression$Graph.class │ │ ├── DSUrankPathCompression$Pair.class │ │ └── DSUrankPathCompression.class │ │ ├── EulerTour │ │ ├── EulerTour.class │ │ └── bestEulerTour.class │ │ ├── FloodFill │ │ ├── MakeLargestIsland.class │ │ ├── alphabetMatch.class │ │ ├── colorCount.class │ │ ├── graphInput.class │ │ ├── largestIsland.class │ │ └── totalConnectedComponent.class │ │ ├── GraphRepresentation │ │ ├── adj_list_01$Graph.class │ │ ├── adj_list_01.class │ │ ├── adj_list_02$Graph.class │ │ ├── adj_list_02$Node.class │ │ ├── adj_list_02.class │ │ ├── adj_list_02_node$Graph.class │ │ ├── adj_list_02_node$Node.class │ │ └── adj_list_02_node.class │ │ ├── LCA │ │ ├── _2Pointer.class │ │ └── sparseTable.class │ │ ├── MinimumSpanningTree │ │ ├── Kruskal$DSU.class │ │ ├── Kruskal$Graph$1.class │ │ ├── Kruskal$Graph.class │ │ ├── Kruskal.class │ │ ├── Prims$Graph$1.class │ │ ├── Prims$Graph.class │ │ ├── Prims$Pair.class │ │ └── Prims.class │ │ ├── NetworkFlow │ │ ├── dinicsAlgo$Dinic$edge.class │ │ ├── dinicsAlgo$Dinic.class │ │ └── dinicsAlgo.class │ │ ├── ReRooting │ │ ├── Rerooting.class │ │ └── bruteForce.class │ │ ├── ShortestPath │ │ ├── Djikstra$Graph.class │ │ ├── Djikstra$Pair.class │ │ ├── Djikstra.class │ │ ├── FloydWarshal.class │ │ ├── ShortestPathGrid$Node.class │ │ ├── ShortestPathGrid.class │ │ └── bellmanFord.class │ │ ├── StronglyConnectedComponent │ │ ├── KosarajuAlgorithm.class │ │ └── TopologicalOrder.class │ │ ├── TravellingSalesMan │ │ └── travellingSalesMan.class │ │ ├── Trees │ │ └── AncestorPrinting.class │ │ └── multiSourceBfs │ │ ├── BFSMinimumOperations$Pair.class │ │ ├── BFSMinimumOperations.class │ │ ├── MinimumDistance$Pair.class │ │ ├── MinimumDistance.class │ │ ├── ShortestPathFirstToLastRow$Pair.class │ │ └── ShortestPathFirstToLastRow.class └── src │ ├── ArticulationPointAndBridges │ └── ArticulationPointAndBridges.java │ ├── Bonus │ └── BoardGame.java │ ├── BreadthFirstSearch │ ├── Bfs.java │ ├── BfsShortestPath.java │ └── snakesAndLadder.java │ ├── CycleDetection │ ├── Bipartite.java │ ├── CycleDetectionDirected.java │ └── CycleDetectionUndirected.java │ ├── DepthFirstSearch │ ├── LongestPathSequence.java │ ├── dfs.java │ ├── largestIsland.java │ └── largestIslandCopy.java │ ├── DfsTreesAndBackEdges │ ├── CycleInGraph.java │ ├── DfsTreesAndBackEdges.java │ └── DfsTreesAndBackEdgesDirected.java │ ├── DirectedAcyclicGraph │ ├── topologicalBFS.java │ ├── topologicalDFS.java │ └── topologicalSort.java │ ├── DisjointSetUnion │ ├── DSU_1.java │ ├── DSU_2.java │ └── DSUrankPathCompression.java │ ├── EulerTour │ ├── EulerTour.java │ └── bestEulerTour.java │ ├── FloodFill │ ├── MakeLargestIsland.java │ ├── alphabetMatch.java │ ├── colorCount.java │ ├── graphInput.java │ ├── largestIsland.java │ └── totalConnectedComponent.java │ ├── GraphRepresentation │ ├── adj_list_01.java │ ├── adj_list_02.java │ └── adj_list_02_node.java │ ├── LCA │ ├── _2Pointer.java │ └── sparseTable.java │ ├── MinimumSpanningTree │ ├── Kruskal.java │ └── Prims.java │ ├── NetworkFlow │ └── dinicsAlgo.java │ ├── ReRooting │ ├── Rerooting.java │ └── bruteForce.java │ ├── ShortestPath │ ├── Djikstra.java │ ├── FloydWarshal.java │ ├── ShortestPathGrid.java │ └── bellmanFord.java │ ├── StronglyConnectedComponent │ ├── KosarajuAlgorithm.java │ └── TopologicalOrder.java │ ├── TravellingSalesMan │ └── travellingSalesMan.java │ ├── Trees │ └── AncestorPrinting.java │ └── multiSourceBfs │ ├── BFSMinimumOperations.java │ ├── MinimumDistance.java │ └── ShortestPathFirstToLastRow.java └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/.DS_Store -------------------------------------------------------------------------------- /Graphs C++/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs C++/.DS_Store -------------------------------------------------------------------------------- /Graphs C++/01 - Graph Representation/01_adj_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | class Graph{ 7 | 8 | int V; 9 | list *l; 10 | 11 | public: 12 | Graph(int v){ 13 | V = v; 14 | l = new list[V]; 15 | } 16 | 17 | void addEdge(int i,int j,bool undir=true){ 18 | l[i].push_back(j); 19 | if(undir){ 20 | l[j].push_back(i); 21 | } 22 | } 23 | 24 | void printAdjList(){ 25 | //Iterate over all the rows 26 | for(int i=0;i"; 28 | //every element of ith linked list 29 | for(auto node:l[i]){ 30 | cout << node <<","; 31 | } 32 | cout < 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Node{ 9 | public: 10 | string name; 11 | list nbrs; 12 | 13 | Node(string name){ 14 | this->name = name; 15 | } 16 | }; 17 | 18 | class Graph{ 19 | unordered_map m; 20 | 21 | public: 22 | Graph(vector cities){ 23 | for(auto city : cities){ 24 | m[city] = new Node(city); 25 | } 26 | } 27 | 28 | void addEdge(string x,string y,bool undir=false){ 29 | m[x]->nbrs.push_back(y); 30 | 31 | if(undir){ 32 | m[y]->nbrs.push_back(x); 33 | } 34 | } 35 | 36 | void printAdjList(){ 37 | for(auto cityPair : m){ 38 | auto city = cityPair.first; 39 | Node *node = cityPair.second; 40 | cout<"; 41 | for(auto nbr : node->nbrs){ 42 | cout << nbr<<","; 43 | } 44 | cout< cities = {"Delhi","London","Paris","New York"}; 51 | Graph g(cities); 52 | 53 | g.addEdge("Delhi","London"); 54 | g.addEdge("New York","London"); 55 | g.addEdge("Delhi","Paris"); 56 | g.addEdge("Paris","New York"); 57 | 58 | g.printAdjList(); 59 | 60 | 61 | return 0; 62 | } 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /Graphs C++/01 - Graph Representation/02_adj_list_node.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | class Node{ 10 | public: 11 | string name; 12 | list nbrs; 13 | 14 | Node(string name){ 15 | this->name = name; 16 | } 17 | }; 18 | 19 | class Graph{ 20 | //Node Name -- Pointer to Node Object 21 | unordered_map m; 22 | public: 23 | Graph(vector cities){ 24 | for(auto city : cities){ 25 | m[city] = new Node(city); 26 | } 27 | } 28 | 29 | void addEdge(string x,string y,bool undir=false){ 30 | m[x]->nbrs.push_back(y); 31 | if(undir){ 32 | m[y]->nbrs.push_back(x); 33 | } 34 | } 35 | 36 | void printAdjList(){ 37 | for(auto cityPair : m){ 38 | auto city = cityPair.first; 39 | cout<"; 40 | Node *node = cityPair.second; 41 | for(auto nbr : node->nbrs){ 42 | cout< cities = {"Delhi","London","Paris","New York"}; 52 | Graph g(cities); 53 | g.addEdge("Delhi","London"); 54 | g.addEdge("New York","London"); 55 | g.addEdge("Delhi","Paris"); 56 | g.addEdge("Paris","New York"); 57 | 58 | g.printAdjList(); 59 | 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Graphs C++/02 - Breadth First Search/03_bfs_.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Graph{ 8 | 9 | int V; 10 | list *l; 11 | 12 | public: 13 | Graph(int v){ 14 | V = v; 15 | l = new list[V]; 16 | } 17 | 18 | void addEdge(int i,int j,bool undir=true){ 19 | l[i].push_back(j); 20 | if(undir){ 21 | l[j].push_back(i); 22 | } 23 | } 24 | void bfs(int source){ 25 | 26 | queue q; 27 | bool *visited = new bool[V]{0}; 28 | 29 | q.push(source); 30 | visited[source] = true; 31 | 32 | while(!q.empty()){ 33 | //Do some work for every node 34 | int f = q.front(); 35 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Graph{ 8 | 9 | int V; 10 | list *l; 11 | 12 | public: 13 | Graph(int v){ 14 | V = v; 15 | l = new list[V]; 16 | } 17 | 18 | void addEdge(int i,int j,bool undir=true){ 19 | l[i].push_back(j); 20 | if(undir){ 21 | l[j].push_back(i); 22 | } 23 | } 24 | void bfs(int source,int dest=-1){ 25 | 26 | queue q; 27 | bool *visited = new bool[V]{0}; 28 | int *dist = new int[V]{0}; 29 | int *parent = new int[V]; 30 | 31 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | list *l; 8 | int V; 9 | 10 | public: 11 | Graph(int V){ 12 | this->V = V; 13 | l = new list[V+1]; 14 | } 15 | void addEdge(int u,int v){ 16 | l[u].push_back(v); 17 | } 18 | 19 | int minCostBFS(int src,int dest){ 20 | queue q; 21 | vector visited(V,false); 22 | vector dist(V,0); 23 | 24 | q.push(src); 25 | visited[src] = true; 26 | dist[src] = 0; 27 | 28 | while(!q.empty()){ 29 | int f = q.front(); 30 | q.pop(); 31 | 32 | for(int nbr : l[f]){ 33 | if(!visited[nbr]){ 34 | q.push(nbr); 35 | visited[nbr] = true; 36 | dist[nbr] = dist[f] + 1; 37 | } 38 | } 39 | } 40 | return dist[dest]; 41 | } 42 | 43 | }; 44 | 45 | 46 | 47 | int min_dice_throws(int n,vector > snakes, vector > ladders){ 48 | vector board(n+1,0); 49 | 50 | //board to graph conversion 51 | for(auto sp: snakes){ 52 | int s = sp.first; 53 | int e = sp.second; 54 | board[s] = e - s; 55 | } 56 | 57 | for(auto lp: ladders){ 58 | int s = lp.first; 59 | int e = lp.second; 60 | board[s] = e - s; 61 | } 62 | 63 | //Graph 64 | Graph g(n+1); 65 | for(int u=1;u 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Graph{ 8 | 9 | int V; 10 | list *l; 11 | 12 | public: 13 | Graph(int v){ 14 | V = v; 15 | l = new list[V]; 16 | } 17 | 18 | void addEdge(int i,int j,bool undir=true){ 19 | l[i].push_back(j); 20 | if(undir){ 21 | l[j].push_back(i); 22 | } 23 | } 24 | void dfsHelper(int node,bool *visited){ 25 | visited[node] = true; 26 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int dfs(vector > &matrix, vector > &visited, int i,int j,int m,int n){ 6 | 7 | visited[i][j] = true; 8 | 9 | int cs = 1; 10 | 11 | int dx[] = {1,-1,0,0}; 12 | int dy[] = {0,0,1,-1}; 13 | 14 | for(int k=0;k<4;k++){ 15 | int nx = i + dx[k]; 16 | int ny = j + dy[k]; 17 | 18 | if(nx>=0 and nx=0 and ny > matrix){ 28 | //return the size of largest island in grid 29 | int m = matrix.size(); 30 | int n = matrix[0].size(); 31 | 32 | //visited matrix 33 | vector > visited(m, vector(n,false)); 34 | 35 | int largest = 0; 36 | 37 | for(int i=0;ilargest){ 43 | largest = size; 44 | } 45 | 46 | } 47 | 48 | } 49 | } 50 | return largest; 51 | } 52 | 53 | 54 | int main(){ 55 | vector > grid = { 56 | {1, 0, 0, 1, 0}, 57 | {1, 0, 1, 0, 0}, 58 | {0, 0, 1, 0, 1}, 59 | {1, 0, 1, 1, 1}, 60 | {1, 0, 1, 1, 0} 61 | }; 62 | 63 | cout<< largest_island(grid) < 2 | #include 3 | using namespace std; 4 | 5 | int dfs(vector > &matrix, vector > &visited, int i,int j,int m,int n){ 6 | 7 | visited[i][j] = true; 8 | 9 | int cs = 1; 10 | 11 | int dx[] = {1,-1,0,0}; 12 | int dy[] = {0,0,1,-1}; 13 | 14 | for(int k=0;k<4;k++){ 15 | int nx = i + dx[k]; 16 | int ny = j + dy[k]; 17 | 18 | if(nx>=0 and nx=0 and ny > matrix){ 28 | //return the size of largest island in grid 29 | int m = matrix.size(); 30 | int n = matrix[0].size(); 31 | 32 | //visited matrix 33 | vector > visited(m, vector(n,false)); 34 | 35 | int largest = 0; 36 | 37 | for(int i=0;ilargest){ 43 | largest = size; 44 | } 45 | 46 | } 47 | 48 | } 49 | } 50 | return largest; 51 | } 52 | 53 | 54 | int main(){ 55 | vector > grid = { 56 | {1, 0, 0, 1, 0}, 57 | {1, 0, 1, 0, 0}, 58 | {0, 0, 1, 0, 1}, 59 | {1, 0, 1, 1, 1}, 60 | {1, 0, 1, 1, 0} 61 | }; 62 | 63 | cout<< largest_island(grid) < 2 | using namespace std; 3 | 4 | 5 | void dfs(vector> matrix,vector > &visited, vector > &cache, int i,int j,int m,int n){ 6 | 7 | visited[i][j] = 1; 8 | 9 | int dx[] = {-1,1,0,0}; 10 | int dy[] = {0,0,1,-1}; 11 | 12 | int cnt = 0; 13 | for(int k=0;k<4;k++){ 14 | int nx = i + dx[k]; 15 | int ny = j + dy[k]; 16 | 17 | if(nx>=0 and ny>=0 and nxmatrix[i][j]){ 18 | int subProblemCnt = 0; 19 | if(visited[nx][ny]){ 20 | cnt = max(cnt,1+cache[nx][ny]); 21 | } 22 | else{ 23 | dfs(matrix,visited,cache,nx,ny,m,n); 24 | cnt = max(cnt,1+cache[nx][ny]); 25 | } 26 | } 27 | } 28 | cache[i][j] = cnt; 29 | return; 30 | } 31 | 32 | int longestPathSequence(vector> matrix) { 33 | // Write your code here. 34 | int m = matrix.size(); 35 | int n = matrix[0].size(); 36 | vector > visited(m+1,vector(n+1,0)); 37 | vector > cache(m+1,vector(n+1,0)); 38 | //do a dfs from every cell //and store the length of of maximum len seq startinf from that cell 39 | int ans = 0; 40 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | bool dfs_helper(vector graph[],int node,int *visited,int parent, int color){ 6 | //come to node 7 | visited[node] = color; //1 or 2, both mean visited 8 | 9 | for(auto nbr : graph[node]){ 10 | 11 | if(visited[nbr]==0){ 12 | int subprob = dfs_helper(graph,nbr,visited,node,3-color); 13 | 14 | if(subprob==false){ 15 | return false; 16 | } 17 | 18 | } 19 | else if(nbr!=parent and color==visited[nbr]){ 20 | return false; 21 | } 22 | 23 | } 24 | return true; 25 | } 26 | 27 | 28 | bool dfs(vector graph[],int N){ 29 | 30 | int visited[N] = {0}; // 0- Not Visited, 1 - Visited Color is 1, 2 - Visted Color 2 31 | 32 | int color = 1; 33 | int ans = dfs_helper(graph,0,visited,-1,color); 34 | //later one 35 | 36 | //colors 37 | for(int i=0;i>N>>M; 50 | 51 | vector graph[N]; 52 | while(M--){ 53 | int x,y; 54 | cin>>x>>y; 55 | 56 | graph[x].push_back(y); 57 | graph[y].push_back(x); 58 | 59 | } 60 | 61 | //BFS or DFS, by coloring the nodes at each step (current node has color 1, nbr should have a color 2) 62 | if(dfs(graph,N)){ 63 | cout<<"Yes its bipartite"; 64 | } 65 | else{ 66 | cout<<"Not bipartite"; 67 | } 68 | 69 | 70 | 71 | return 0; 72 | } 73 | 74 | -------------------------------------------------------------------------------- /Graphs C++/04 - Cycle Detection/cycle_detection_directed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | list *l; 8 | int V; 9 | 10 | public: 11 | Graph(int V){ 12 | this->V = V; 13 | l = new list[V]; 14 | } 15 | 16 | void addEdge(int x,int y){ 17 | l[x].push_back(y); 18 | } 19 | 20 | bool dfs(int node,vector &visited, vector &stack){ 21 | //arrive at node 22 | visited[node] = true; 23 | stack[node] = true; 24 | 25 | //do some work at node,return true if backedge is found here itself 26 | for(int nbr : l[node]){ 27 | 28 | if(stack[nbr]==true){ 29 | return true; 30 | } 31 | else if(visited[nbr]==false){ 32 | bool nbrFoundACycle = dfs(nbr,visited,stack); 33 | if(nbrFoundACycle){ 34 | return true; 35 | } 36 | } 37 | } 38 | 39 | //going back 40 | stack[node] = false; 41 | return false; 42 | } 43 | 44 | bool contains_cycle(){ 45 | vector visited(V,false); 46 | vector stack(V,false); 47 | 48 | for(int i=0;i > edges){ 63 | //Complete this method 64 | 65 | Graph g(V); 66 | for(auto edge : edges){ 67 | g.addEdge(edge.first,edge.second); 68 | } 69 | return g.contains_cycle(); 70 | 71 | } 72 | 73 | int main(){ 74 | 75 | Graph g(3); 76 | g.addEdge(0,1); 77 | g.addEdge(1,2); 78 | g.addEdge(2,0); 79 | 80 | cout << g.contains_cycle() < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | list *l; 8 | int V; 9 | 10 | public: 11 | Graph(int V){ 12 | this->V = V; 13 | l = new list[V]; 14 | } 15 | 16 | //undirected graph 17 | void addEdge(int x,int y){ 18 | l[x].push_back(y); 19 | l[y].push_back(x); 20 | } 21 | bool dfs(int node, vector &visited, int parent){ 22 | //mark that node visited 23 | visited[node] = true; 24 | 25 | for(auto nbr : l[node]){ 26 | 27 | if(!visited[nbr]){ 28 | 29 | bool nbrFoundACycle = dfs(nbr,visited,node); 30 | if(nbrFoundACycle){ 31 | return true; 32 | } 33 | } 34 | //nbr is visited and its not the parent of current node in the current dfs call 35 | else if(nbr!=parent){ 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | bool contains_cycle(){ 43 | //Graph is single component 44 | vector visited(V,false); 45 | return dfs(0, visited, -1); 46 | } 47 | 48 | }; 49 | 50 | bool contains_cycle(int V,vector > edges){ 51 | //Complete this method 52 | 53 | Graph g(V); 54 | for(auto edge:edges){ 55 | g.addEdge(edge.first,edge.second); 56 | } 57 | return g.contains_cycle(); 58 | 59 | } 60 | 61 | int main(){ 62 | 63 | Graph g(3); 64 | g.addEdge(0,1); 65 | g.addEdge(1,2); 66 | //g.addEdge(2,0); 67 | 68 | cout << g.contains_cycle() < 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Graph { 10 | 11 | list *l; 12 | int V; 13 | 14 | public: 15 | Graph(int V) { 16 | this->V = V; 17 | l = new list[V]; 18 | } 19 | 20 | void addEdge(int x, int y) { 21 | //directed graph 22 | l[x].push_back(y); 23 | } 24 | //Complete this method 25 | void topological_sort() { 26 | vector indegree(V,0); 27 | 28 | //Iterate over all the edges to find the right indegree 29 | for(int i=0;i q; 38 | //init the q with nodes having 0 indegree 39 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Graph { 10 | 11 | list *l; 12 | int V; 13 | 14 | public: 15 | Graph(int V) { 16 | this->V = V; 17 | l = new list[V]; 18 | } 19 | 20 | void addEdge(int x, int y) { 21 | //directed graph 22 | l[x].push_back(y); 23 | } 24 | void dfs(int node, vector &visited, list &ordering){ 25 | 26 | visited[node] = true; 27 | 28 | for(int nbr : l[node]){ 29 | if(!visited[nbr]){ 30 | dfs(nbr,visited,ordering); 31 | } 32 | } 33 | //at this point 34 | ordering.push_front(node); 35 | return; 36 | 37 | } 38 | 39 | //Complete this method 40 | void dfs_topological_sort() { 41 | 42 | vector visited(V,false); 43 | list ordering; 44 | 45 | //we call dfs from every node if it not visited 46 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Graph{ 8 | int V; 9 | public: 10 | list *l; 11 | 12 | Graph(int v){ 13 | V = v; 14 | l = new list[V]; 15 | } 16 | 17 | void addEdge(int u,int v,bool bidir=true){ 18 | l[u].push_back(v); 19 | if(bidir){ 20 | l[v].push_back(u); 21 | } 22 | } 23 | //Iterate using a loop - Breadth First Search 24 | void bfs(int s){ 25 | queue q; 26 | q.push(s); 27 | 28 | 29 | int *dist = new int[V]; 30 | //Init all nodes with inf dist 31 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | //Cycle Detection in a undirected graph using DSU 6 | 7 | class Graph{ 8 | int V; 9 | list > l; 10 | 11 | public: 12 | Graph(int V){ 13 | this->V = V; 14 | } 15 | 16 | int addEdge(int u,int v){ 17 | l.push_back(make_pair(u,v)); 18 | } 19 | // Find 20 | int findSet(int i,int parent[]){ 21 | //base case 22 | if(parent[i]==-1){ 23 | return i; 24 | } 25 | 26 | return findSet(parent[i],parent); 27 | } 28 | 29 | 30 | //Union 31 | void union_set(int x,int y,int parent[]){ 32 | int s1 = findSet(x,parent); 33 | int s2 = findSet(y,parent); 34 | 35 | if(s1!=s2){ 36 | parent[s1] = s2; 37 | } 38 | } 39 | 40 | 41 | bool contains_cycle(){ 42 | //DSU Logic to check if graph contains cycle or not 43 | int *parent = new int[V]; 44 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | //Cycle Detection in a undirected graph using DSU 6 | 7 | class Graph{ 8 | int V; 9 | list > l; 10 | 11 | public: 12 | Graph(int V){ 13 | this->V = V; 14 | } 15 | 16 | int addEdge(int u,int v){ 17 | l.push_back(make_pair(u,v)); 18 | } 19 | // Find 20 | int findSet(int i,int parent[]){ 21 | //base case 22 | if(parent[i]==-1){ 23 | return i; 24 | } 25 | //path compression optimisation 26 | return parent[i] = findSet(parent[i],parent); 27 | } 28 | 29 | 30 | //Union 31 | void union_set(int x,int y,int parent[],int rank[]){ 32 | int s1 = findSet(x,parent); 33 | int s2 = findSet(y,parent); 34 | 35 | if(s1!=s2){ 36 | if(rank[s1] 2 | #include 3 | using namespace std; 4 | 5 | 6 | 7 | class Graph{ 8 | 9 | list > edge_list; 10 | int V; 11 | 12 | 13 | public: 14 | Graph(int V){ 15 | this->V = V; 16 | } 17 | 18 | void addEdge(int u,int v){ 19 | edge_list.push_back(make_pair(u,v)); 20 | } 21 | 22 | int findSet(int i,int parent[]){ 23 | if(parent[i]==-1){ 24 | return i; 25 | } 26 | int p = findSet(parent[i],parent); 27 | //compress the path for next time 28 | parent[i] = p; 29 | return p; 30 | 31 | } 32 | void union_set(int u,int v,int rank[],int parent[]){ 33 | 34 | int p1 = findSet(u,parent); 35 | int p2 = findSet(v,parent); 36 | 37 | if(p1!=p2){ 38 | if(rank[p1] 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | //DSU Data Structure 8 | //Path Compression + Union By Rank 9 | 10 | class DSU{ 11 | 12 | int *parent; 13 | int *rank; 14 | 15 | public: 16 | DSU(int n){ 17 | parent = new int[n]; 18 | rank = new int[n]; 19 | 20 | //parent -1, rank = 1 21 | for(int i=0;i > edgelist; 63 | int V; 64 | 65 | public: 66 | Graph(int V){ 67 | this->V = V; 68 | } 69 | 70 | void addEdge(int x,int y,int w){ 71 | edgelist.push_back({w,x,y}); 72 | } 73 | int kruskal_mst(){ 74 | //Main Logic = Easy!!! 75 | //1. Sort all the edges based upon weight 76 | sort(edgelist.begin(),edgelist.end()); 77 | 78 | //Init a DSU 79 | DSU s(V); 80 | 81 | int ans = 0; 82 | for(auto edge : edgelist){ 83 | 84 | int w = edge[0]; 85 | int x = edge[1]; 86 | int y = edge[2]; 87 | 88 | //take that edge in MST if it doesnt form a cycle 89 | if(s.find(x)!=s.find(y)){ 90 | s.unite(x,y); 91 | ans += w; 92 | } 93 | 94 | } 95 | return ans; 96 | } 97 | 98 | }; 99 | 100 | int main(){ 101 | 102 | /* 103 | Graph g(4); 104 | g.addEdge(0,1,1); 105 | g.addEdge(1,3,3); 106 | g.addEdge(3,2,4); 107 | g.addEdge(2,0,2); 108 | g.addEdge(0,3,2); 109 | g.addEdge(1,2,2); 110 | */ 111 | int n,m; 112 | cin>>n>>m; 113 | 114 | Graph g(n); 115 | for(int i=0;i>x>>y>>w; 118 | g.addEdge(x-1,y-1,w); 119 | } 120 | 121 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | 8 | //Adjacency. List 9 | vector > *l; 10 | int V; 11 | 12 | public: 13 | Graph(int n){ 14 | V = n; 15 | l = new vector >[n]; 16 | } 17 | 18 | void addEdge(int x,int y,int w){ 19 | l[x].push_back({y,w}); 20 | l[y].push_back({x,w}); 21 | } 22 | 23 | int prim_mst(){ 24 | //most important stuff 25 | //Init a Min Heap 26 | priority_queue, vector > , greater > > Q; 27 | 28 | //another array 29 | //visited array that denotes whether a node has been included in MST or Not 30 | bool * vis = new bool[V]{0}; 31 | int ans = 0; 32 | 33 | //begin 34 | Q.push({0,0}); // weight, node 35 | 36 | while(!Q.empty()){ 37 | //pick out the edge with min weight 38 | auto best = Q.top(); 39 | Q.pop(); 40 | 41 | int to = best.second; 42 | int weight = best.first; 43 | 44 | if(vis[to]){ 45 | //discard the edge, and continue 46 | continue; 47 | } 48 | 49 | //otherwise take the current edge 50 | ans += weight; 51 | vis[to] = 1; 52 | 53 | //add the new edges in the queue 54 | for(auto x:l[to]){ 55 | if(vis[x.first]==0){ 56 | Q.push({x.second,x.first}); 57 | } 58 | } 59 | } 60 | return ans; 61 | } 62 | 63 | }; 64 | 65 | int main(){ 66 | 67 | int n,m; 68 | cin>>n>>m; 69 | 70 | Graph g(n); 71 | for(int i=0;i>x>>y>>w; 74 | g.addEdge(x-1,y-1,w); 75 | } 76 | 77 | cout< 2 | #include 3 | using namespace std; 4 | 5 | 6 | vector bellman_ford(int V,int src,vector > edges){ 7 | 8 | //create a vector 9 | vector dist(V+1,INT_MAX); 10 | dist[src] = 0; 11 | 12 | //relax all edges v-1 times 13 | for(int i=0;i>n>>m; 46 | 47 | 48 | 49 | //edge list 50 | vector > edges; // (a,b,3) (c,d,5) .... 51 | 52 | for(int i=0;i>u>>v>>wt; 55 | edges.push_back({u,v,wt}); 56 | } 57 | //bellman algorithm 58 | 59 | vector distances = bellman_ford(n,1,edges); 60 | 61 | for(int i=1;i<=n;i++){ 62 | cout<<"Node "< 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Graph{ 9 | 10 | int V; 11 | list > *l; 12 | 13 | public: 14 | Graph(int v){ 15 | V = v; 16 | l = new list >[V]; 17 | } 18 | 19 | void addEdge(int u,int v,int wt,bool undir = true){ 20 | 21 | l[u].push_back({wt,v}); 22 | if(undir){ 23 | l[v].push_back({wt,u}); 24 | } 25 | } 26 | 27 | int dijkstra(int src,int dest){ 28 | 29 | //Data Structures 30 | vector dist(V,INT_MAX); 31 | set > s; 32 | 33 | //1. Init 34 | dist[src] = 0; 35 | s.insert({0,src}); 36 | 37 | while(!s.empty()){ 38 | 39 | auto it = s.begin(); 40 | int node = it->second; 41 | int distTillNow = it->first; 42 | s.erase(it); //Pop 43 | 44 | //Iterate over the nbrs of node 45 | for(auto nbrPair : l[node]){ 46 | //...... 47 | 48 | int nbr = nbrPair.second; 49 | int currentEdge = nbrPair.first; 50 | 51 | if(distTillNow + currentEdge < dist[nbr]){ 52 | //remove if nbr already exist in the set 53 | 54 | auto f = s.find({dist[nbr],nbr}); 55 | if(f!=s.end()){ 56 | s.erase(f); 57 | } 58 | //insert the updated value with the new dist 59 | dist[nbr] = distTillNow + currentEdge; 60 | s.insert({dist[nbr],nbr}); 61 | 62 | } 63 | 64 | } 65 | 66 | } 67 | //Single Source Shortest Dist to all other nodes 68 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | #define INF 10000 6 | 7 | vector > floyd_warshall(vector > graph){ 8 | 9 | vector > dist(graph); 10 | 11 | int V = graph.size(); 12 | 13 | //Phases, in kth phase we included vertices (1,2,...k) as intermediate vertices 14 | for(int k=0;k dist[i][k] + dist[k][j]){ 21 | dist[i][j] = dist[i][k] + dist[k][j]; 22 | } 23 | } 24 | 25 | } 26 | } 27 | return dist; 28 | } 29 | 30 | 31 | int main(){ 32 | 33 | 34 | // 4 Vertices (4 X 4 Matrix) 35 | vector > graph = { 36 | {0,INF,-2,INF}, 37 | {4,0,3,INF}, 38 | {INF,INF,0,2}, 39 | {INF,-1,INF,0} 40 | }; 41 | 42 | 43 | auto result = floyd_warshall(graph); 44 | for(int i=0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Node{ 7 | public: 8 | int x; 9 | int y; 10 | int dist; 11 | 12 | Node(int x,int y,int dist){ 13 | this-> x = x; 14 | this->y = y; 15 | this->dist = dist; 16 | } 17 | }; 18 | 19 | //comparator should return boolean value, 20 | // indicating whether the element passed as 21 | // first argument is considered to go before the second in the specific strict weak ordering 22 | class Compare{ 23 | public: 24 | bool operator()(const Node &a,const Node &b){ 25 | return a.dist <= b.dist; 26 | } 27 | }; 28 | 29 | 30 | int shortest_path(vector > grid){ 31 | //return the shortest path len 32 | 33 | int m = grid.size(); 34 | int n = grid[0].size(); 35 | 36 | int i = 0; 37 | int j = 0; 38 | 39 | //2D vector to denote of each cell 40 | vector > dist(m+1, vector(n+1,INT_MAX)); 41 | 42 | dist[i][j] = grid[0][0]; 43 | set s; 44 | 45 | s.insert(Node(0,0,dist[0][0])); 46 | 47 | int dx[] = {0,0,1,-1}; 48 | int dy[] = {1,-1,0,0}; 49 | 50 | 51 | while(!s.empty()){ 52 | 53 | auto it = s.begin(); 54 | int cx = it->x; 55 | int cy = it->y; 56 | int cd = it->dist; 57 | s.erase(it); 58 | 59 | //update nbrs 60 | for(int k=0;k<4;k++){ 61 | int nx = cx + dx[k]; 62 | int ny = cy + dy[k]; 63 | 64 | if(nx>=0 and nx=0 and ny 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | int tsp(vector > dist, int setOfCities, int city,int n,vector > &dp){ 8 | 9 | //base case 10 | if(setOfCities == (1< > dist = { 38 | {0,20,42,25}, 39 | {20,0,30,34}, 40 | {42,30,0,10}, 41 | {25,34,10,0} 42 | }; 43 | int n = 4; 44 | 45 | vector< vector > dp(1<(n,-1)); 46 | 47 | cout << tsp(dist,1,0,n,dp)< 2 | 3 | using namespace std; 4 | 5 | const int N = 100; 6 | 7 | int a[N][N]; 8 | 9 | int n, m; 10 | 11 | int dx[4] = {0, 0, 1, -1}; 12 | int dy[4] = {1, -1, 0, 0}; 13 | 14 | void flood_fill(int x, int y) { 15 | a[x][y] = 0; 16 | for (int i = 0; i < 4; i++) { 17 | int xx = x + dx[i]; 18 | int yy = y + dy[i]; 19 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && a[xx][yy] == 1) { 20 | flood_fill(xx, yy); 21 | } 22 | } 23 | } 24 | 25 | int main() 26 | { 27 | freopen("input.txt", "r", stdin); 28 | freopen("output.txt", "w", stdout); 29 | 30 | cin >> n >> m; 31 | for (int i = 0; i < n; i++) { 32 | for (int j = 0; j < m; j++) { 33 | cin >> a[i][j]; 34 | } 35 | } 36 | 37 | int total_count = 0; 38 | 39 | for (int i = 0; i < n; i++) { 40 | for (int j = 0; j < m; j++) { 41 | if (a[i][j] == 1) { 42 | total_count++; 43 | flood_fill(i, j); 44 | } 45 | } 46 | } 47 | 48 | cout << total_count; 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Graphs C++/10 - Flood Fill /Flood Fill alphabet match.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 100; 6 | 7 | int a[N][N], vis[N][N]; 8 | 9 | int n, m; 10 | 11 | int dx[4] = {0, 0, 1, -1}; 12 | int dy[4] = {1, -1, 0, 0}; 13 | 14 | void flood_fill(int x, int y, int col) { 15 | vis[x][y] = 1; 16 | for (int i = 0; i < 4; i++) { 17 | int xx = x + dx[i]; 18 | int yy = y + dy[i]; 19 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && a[x][y] == a[xx][yy] && !vis[xx][yy]) { 20 | flood_fill(xx, yy, col); 21 | } 22 | } 23 | a[x][y] = col; 24 | } 25 | 26 | int main() 27 | { 28 | freopen("input.txt", "r", stdin); 29 | freopen("output.txt", "w", stdout); 30 | 31 | cin >> n >> m; 32 | for (int i = 0; i < n; i++) { 33 | for (int j = 0; j < m; j++) { 34 | char ch; 35 | cin >> ch; 36 | a[i][j] = ch - 'A' + 1; 37 | } 38 | } 39 | 40 | int col = 0; 41 | 42 | for (int i = 0; i < n; i++) { 43 | for (int j = 0; j < m; j++) { 44 | if (!vis[i][j]) { 45 | col++; 46 | flood_fill(i, j, col); 47 | } 48 | } 49 | } 50 | 51 | for (int i = 0; i < n; i++) { 52 | for (int j = 0; j < m; j++) { 53 | cout << a[i][j] << " "; 54 | } cout << '\n'; 55 | } 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Graphs C++/10 - Flood Fill /Flood Fill make largest island.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 100; 6 | 7 | int a[N][N], vis[N][N]; 8 | int col_cnt[N]; 9 | 10 | int n, m; 11 | 12 | int dx[4] = {0, 0, 1, -1}; 13 | int dy[4] = {1, -1, 0, 0}; 14 | 15 | void flood_fill(int x, int y, int col) { 16 | a[x][y] = col; 17 | col_cnt[col]++; 18 | vis[x][y] = 1; 19 | for (int i = 0; i < 4; i++) { 20 | int xx = x + dx[i]; 21 | int yy = y + dy[i]; 22 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && vis[xx][yy] == 0 && a[xx][yy] == 1) { 23 | flood_fill(xx, yy, col); 24 | } 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | freopen("input.txt", "r", stdin); 31 | freopen("output.txt", "w", stdout); 32 | 33 | cin >> n >> m; 34 | for (int i = 0; i < n; i++) { 35 | for (int j = 0; j < m; j++) { 36 | cin >> a[i][j]; 37 | } 38 | } 39 | 40 | int total_count = 0; 41 | 42 | for (int i = 0; i < n; i++) { 43 | for (int j = 0; j < m; j++) { 44 | if (a[i][j] == 1 && vis[i][j] == 0) { 45 | total_count++; 46 | flood_fill(i, j, total_count); 47 | } 48 | } 49 | } 50 | 51 | int largest_island = 0; 52 | 53 | for (int i = 1; i <= total_count; i++) { 54 | largest_island = max(largest_island, col_cnt[i]); 55 | } 56 | 57 | for (int i = 0; i < n; i++) { 58 | for (int j = 0; j < m; j++) { 59 | if (a[i][j] == 0) { 60 | // can be converted 61 | set St; 62 | for (int k = 0; k < 4; k++) { 63 | int ii = i + dx[k]; 64 | int jj = j + dy[k]; 65 | if (ii >= 0 && ii < n && jj >= 0 && jj < m) { 66 | St.insert(a[ii][jj]); 67 | } 68 | } 69 | int ans = 1; 70 | for (auto x : St) { 71 | ans += col_cnt[x]; 72 | } 73 | largest_island = max(largest_island, ans); 74 | } 75 | } 76 | } 77 | 78 | cout << largest_island; 79 | 80 | return 0; 81 | } -------------------------------------------------------------------------------- /Graphs C++/10 - Flood Fill /Flood fill color count.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 100; 6 | 7 | int a[N][N], vis[N][N]; 8 | int col_cnt[N]; 9 | 10 | int n, m; 11 | 12 | int dx[4] = {0, 0, 1, -1}; 13 | int dy[4] = {1, -1, 0, 0}; 14 | 15 | void flood_fill(int x, int y, int col) { 16 | a[x][y] = col; 17 | col_cnt[col]++; 18 | vis[x][y] = 1; 19 | for (int i = 0; i < 4; i++) { 20 | int xx = x + dx[i]; 21 | int yy = y + dy[i]; 22 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && vis[xx][yy] == 0 && a[xx][yy] == 1) { 23 | flood_fill(xx, yy, col); 24 | } 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | freopen("input.txt", "r", stdin); 31 | freopen("output.txt", "w", stdout); 32 | 33 | cin >> n >> m; 34 | for (int i = 0; i < n; i++) { 35 | for (int j = 0; j < m; j++) { 36 | cin >> a[i][j]; 37 | } 38 | } 39 | 40 | int total_count = 0; 41 | 42 | for (int i = 0; i < n; i++) { 43 | for (int j = 0; j < m; j++) { 44 | if (a[i][j] == 1 && vis[i][j] == 0) { 45 | total_count++; 46 | flood_fill(i, j, total_count); 47 | } 48 | } 49 | } 50 | 51 | for (int i = 0; i < n; i++) { 52 | for (int j = 0; j < m; j++) { 53 | cout << a[i][j] << " "; 54 | } cout << '\n'; 55 | } 56 | 57 | for (int i = 1; i <= total_count; i++) { 58 | cout << i << " " << col_cnt[i] << '\n'; 59 | } 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Graphs C++/10 - Flood Fill /flood fill largest island.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 100; 6 | 7 | int a[N][N], vis[N][N]; 8 | int col_cnt[N]; 9 | 10 | int n, m; 11 | 12 | int dx[4] = {0, 0, 1, -1}; 13 | int dy[4] = {1, -1, 0, 0}; 14 | 15 | void flood_fill(int x, int y, int col) { 16 | a[x][y] = col; 17 | col_cnt[col]++; 18 | vis[x][y] = 1; 19 | for (int i = 0; i < 4; i++) { 20 | int xx = x + dx[i]; 21 | int yy = y + dy[i]; 22 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && vis[xx][yy] == 0 && a[xx][yy] == 1) { 23 | flood_fill(xx, yy, col); 24 | } 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | freopen("input.txt", "r", stdin); 31 | freopen("output.txt", "w", stdout); 32 | 33 | cin >> n >> m; 34 | for (int i = 0; i < n; i++) { 35 | for (int j = 0; j < m; j++) { 36 | cin >> a[i][j]; 37 | } 38 | } 39 | 40 | int total_count = 0; 41 | 42 | for (int i = 0; i < n; i++) { 43 | for (int j = 0; j < m; j++) { 44 | if (a[i][j] == 1 && vis[i][j] == 0) { 45 | total_count++; 46 | flood_fill(i, j, total_count); 47 | } 48 | } 49 | } 50 | 51 | int largest_island = 0; 52 | 53 | for (int i = 1; i <= total_count; i++) { 54 | largest_island = max(largest_island, col_cnt[i]); 55 | } 56 | 57 | for (int i = 0; i < n; i++) { 58 | for (int j = 0; j < m; j++) { 59 | if (a[i][j] == 0) { 60 | // can be converted 61 | set St; 62 | for (int k = 0; k < 4; k++) { 63 | int ii = i + dx[k]; 64 | int jj = j + dy[k]; 65 | if (ii >= 0 && ii < n && jj >= 0 && jj < m) { 66 | St.insert(a[ii][jj]); 67 | } 68 | } 69 | int ans = 1; 70 | for (auto x : St) { 71 | ans += col_cnt[x]; 72 | } 73 | largest_island = max(largest_island, ans); 74 | } 75 | } 76 | } 77 | 78 | cout << largest_island; 79 | 80 | return 0; 81 | } -------------------------------------------------------------------------------- /Graphs C++/10 - Flood Fill /graph input.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5 + 1; 6 | 7 | vector gr[N]; 8 | 9 | int main() 10 | { 11 | freopen("input.txt", "r", stdin); 12 | freopen("output.txt", "w", stdout); 13 | 14 | int n, m; 15 | cin >> n >> m; 16 | 17 | for (int i = 0; i < m; i++) { 18 | int x, y; 19 | cin >> x >> y; 20 | gr[x].push_back(y); 21 | gr[y].push_back(x); 22 | } 23 | 24 | 25 | 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Graphs C++/11 - Multi Source BFS/Multi source BFS minimum operations .cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | freopen("input.txt", "r", stdin); 8 | freopen("output.txt", "w", stdout); 9 | 10 | int n, m; 11 | cin >> n >> m; 12 | 13 | int a[n][m], dist[n][m]; 14 | queue> Q; 15 | 16 | int dx[4] = {1, -1, 0, 0}; 17 | int dy[4] = {0, 0, 1, -1}; 18 | 19 | for (int i = 0; i < n; i++) { 20 | for (int j = 0; j < m; j++) { 21 | cin >> a[i][j]; 22 | dist[i][j] = INT_MAX; 23 | if (a[i][j]) { 24 | Q.push({i, j}); 25 | dist[i][j] = 0; 26 | } 27 | } 28 | } 29 | 30 | while (!Q.empty()) { 31 | int x = Q.front().first; 32 | int y = Q.front().second; 33 | Q.pop(); 34 | 35 | for (int i = 0; i < 4; i++) { 36 | int xx = x + dx[i]; 37 | int yy = y + dy[i]; 38 | 39 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && dist[xx][yy] == INT_MAX) { 40 | Q.push({xx, yy}); 41 | dist[xx][yy] = dist[x][y] + 1; 42 | } 43 | 44 | } 45 | 46 | for (int i = 0; i < n; i++) { 47 | for (int j = 0; j < m; j++) { 48 | if (dist[i][j] == INT_MAX) cout << "#" << " "; 49 | else cout << dist[i][j] << " "; 50 | } cout << '\n'; 51 | } cout << '\n'; 52 | 53 | 54 | } 55 | 56 | for (int i = 0; i < n; i++) { 57 | for (int j = 0; j < m; j++) { 58 | cout << dist[i][j] << " "; 59 | } cout << '\n'; 60 | } 61 | 62 | return 0; 63 | } -------------------------------------------------------------------------------- /Graphs C++/11 - Multi Source BFS/multisurce BFS (minimum distance).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | freopen("input.txt", "r", stdin); 8 | freopen("output.txt", "w", stdout); 9 | 10 | int n, m; 11 | cin >> n >> m; 12 | 13 | int a[n][m], dist[n][m]; 14 | queue> Q; 15 | 16 | int dx[4] = {1, -1, 0, 0}; 17 | int dy[4] = {0, 0, 1, -1}; 18 | 19 | for (int i = 0; i < n; i++) { 20 | for (int j = 0; j < m; j++) { 21 | cin >> a[i][j]; 22 | dist[i][j] = INT_MAX; 23 | if (a[i][j]) { 24 | Q.push({i, j}); 25 | dist[i][j] = 0; 26 | } 27 | } 28 | } 29 | 30 | while (!Q.empty()) { 31 | int x = Q.front().first; 32 | int y = Q.front().second; 33 | Q.pop(); 34 | 35 | for (int i = 0; i < 4; i++) { 36 | int xx = x + dx[i]; 37 | int yy = y + dy[i]; 38 | 39 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && dist[xx][yy] == INT_MAX) { 40 | Q.push({xx, yy}); 41 | dist[xx][yy] = dist[x][y] + 1; 42 | } 43 | 44 | } 45 | 46 | for (int i = 0; i < n; i++) { 47 | for (int j = 0; j < m; j++) { 48 | if (dist[i][j] == INT_MAX) cout << "#" << " "; 49 | else cout << dist[i][j] << " "; 50 | } cout << '\n'; 51 | } cout << '\n'; 52 | 53 | 54 | } 55 | 56 | for (int i = 0; i < n; i++) { 57 | for (int j = 0; j < m; j++) { 58 | cout << dist[i][j] << " "; 59 | } cout << '\n'; 60 | } 61 | 62 | return 0; 63 | } -------------------------------------------------------------------------------- /Graphs C++/11 - Multi Source BFS/shortest path from first row to last row.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | freopen("input.txt", "r", stdin); 8 | freopen("output.txt", "w", stdout); 9 | 10 | int n, m; 11 | cin >> n >> m; 12 | 13 | int a[n][m], dist[n][m]; 14 | queue> Q; 15 | 16 | int dx[4] = {1, -1, 0, 0}; 17 | int dy[4] = {0, 0, 1, -1}; 18 | 19 | for (int i = 0; i < n; i++) { 20 | for (int j = 0; j < m; j++) { 21 | cin >> a[i][j]; 22 | dist[i][j] = INT_MAX; 23 | if (i == 0 && a[i][j]) { 24 | Q.push({i, j}); 25 | dist[i][j] = 0; 26 | } 27 | } 28 | } 29 | 30 | while (!Q.empty()) { 31 | int x = Q.front().first; 32 | int y = Q.front().second; 33 | Q.pop(); 34 | 35 | if (x == n - 1) { 36 | break; 37 | } 38 | 39 | for (int i = 0; i < 4; i++) { 40 | int xx = x + dx[i]; 41 | int yy = y + dy[i]; 42 | 43 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && dist[xx][yy] == INT_MAX && a[xx][yy] == 1) { 44 | Q.push({xx, yy}); 45 | dist[xx][yy] = dist[x][y] + 1; 46 | } 47 | 48 | } 49 | 50 | // for (int i = 0; i < n; i++) { 51 | // for (int j = 0; j < m; j++) { 52 | // if (dist[i][j] == INT_MAX) cout << "#" << " "; 53 | // else cout << dist[i][j] << " "; 54 | // } cout << '\n'; 55 | // } cout << '\n'; 56 | 57 | 58 | } 59 | 60 | for (int i = 0; i < n; i++) { 61 | for (int j = 0; j < m; j++) { 62 | cout << dist[i][j] << " "; 63 | } cout << '\n'; 64 | } 65 | 66 | int minimum_distance = INT_MAX; 67 | 68 | for (int j = 0; j < m; j++) { 69 | minimum_distance = min(minimum_distance, dist[n - 1][j]); 70 | } 71 | 72 | 73 | return 0; 74 | } -------------------------------------------------------------------------------- /Graphs C++/12 - DFS Tree and Backedges/DFS tree and backedge code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5 + 1; 6 | 7 | vector gr[N]; 8 | int vis[N]; 9 | bool cycle = false; 10 | 11 | void dfs(int cur, int par) { 12 | vis[cur] = 1; 13 | for (auto x : gr[cur]) { 14 | if (!vis[x]) { 15 | dfs(x, cur); 16 | } 17 | else if (x != par) { 18 | cycle = true; 19 | } 20 | } 21 | } 22 | 23 | int main() 24 | { 25 | freopen("input.txt", "r", stdin); 26 | freopen("output.txt", "w", stdout); 27 | 28 | int n, m; 29 | cin >> n >> m; 30 | 31 | for (int i = 0; i < m; i++) { 32 | int x, y; 33 | cin >> x >> y; 34 | gr[x].push_back(y); 35 | gr[y].push_back(x); 36 | 37 | } 38 | 39 | for (int i = 1; i <= n; i++) { 40 | if (!vis[i]) { 41 | dfs(i, 0); 42 | } 43 | } 44 | 45 | if (cycle) { 46 | cout << "Yes cycle found"; 47 | } 48 | else { 49 | cout << "Not found"; 50 | } 51 | 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /Graphs C++/12 - DFS Tree and Backedges/DFS tree and backedges in Directed Graphs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5 + 1; 6 | 7 | vector gr[N]; 8 | int vis[N]; 9 | bool cycle = false; 10 | 11 | void dfs(int cur, int par) { 12 | // visited and in call stack 13 | vis[cur] = 1; 14 | for (auto x : gr[cur]) { 15 | if (vis[x] == 0) { 16 | dfs(x, cur); 17 | } 18 | else if (x != par && vis[x] == 1) { 19 | // backedge 20 | cycle = true; 21 | } 22 | } 23 | // visited and not in call stack 24 | vis[cur] = 2; 25 | return; 26 | } 27 | 28 | int main() 29 | { 30 | freopen("input.txt", "r", stdin); 31 | freopen("output.txt", "w", stdout); 32 | 33 | int n, m; 34 | cin >> n >> m; 35 | 36 | for (int i = 0; i < m; i++) { 37 | int x, y; 38 | cin >> x >> y; 39 | gr[x].push_back(y); 40 | gr[y].push_back(x); 41 | } 42 | 43 | for (int i = 1; i <= n; i++) { 44 | if (vis[i] == 0) { 45 | dfs(i, 0); 46 | } 47 | } 48 | 49 | if (cycle) { 50 | cout << "Yes cycle found"; 51 | } 52 | else { 53 | cout << "Not found"; 54 | } 55 | 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Graphs C++/12 - DFS Tree and Backedges/print cycle in a graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5 + 1; 6 | 7 | vector gr[N]; 8 | int vis[N], Par[N]; 9 | bool cycle = false; 10 | 11 | void dfs(int cur, int par) { 12 | // visited and in call stack 13 | vis[cur] = 1; 14 | Par[cur] = par; 15 | for (auto x : gr[cur]) { 16 | if (vis[x] == 0) { 17 | dfs(x, cur); 18 | } 19 | else if (x != par && vis[x] == 1) { 20 | // backedge 21 | cycle = true; 22 | 23 | int u = cur, v = x; 24 | 25 | while (u != v) { 26 | cout << u << " "; 27 | u = Par[u]; 28 | } 29 | cout << u << " "; 30 | 31 | exit(0); 32 | } 33 | } 34 | // visited and not in call stack 35 | vis[cur] = 2; 36 | return; 37 | } 38 | 39 | int main() 40 | { 41 | freopen("input.txt", "r", stdin); 42 | freopen("output.txt", "w", stdout); 43 | 44 | int n, m; 45 | cin >> n >> m; 46 | 47 | for (int i = 0; i < m; i++) { 48 | int x, y; 49 | cin >> x >> y; 50 | gr[x].push_back(y); 51 | gr[y].push_back(x); 52 | } 53 | 54 | for (int i = 1; i <= n; i++) { 55 | if (vis[i] == 0) { 56 | dfs(i, 0); 57 | } 58 | } 59 | 60 | if (cycle) { 61 | cout << "Yes cycle found"; 62 | } 63 | else { 64 | cout << "Not found"; 65 | } 66 | 67 | 68 | return 0; 69 | } -------------------------------------------------------------------------------- /Graphs C++/13 - Articulation Point and Bridges/articulation point and bridges.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N]; 8 | 9 | int vis[N], disc[N], low[N], tme = 1; 10 | 11 | vector> bridges; 12 | set arti_points; 13 | 14 | void dfs(int cur, int par) { 15 | vis[cur] = 1; 16 | disc[cur] = low[cur] = tme++; 17 | int child = 0; 18 | for (auto x : gr[cur]) { 19 | 20 | if (!vis[x]) { 21 | dfs(x, cur); 22 | child++; 23 | // we know low and disc of x 24 | low[cur] = min(low[cur], low[x]); 25 | 26 | // bridges 27 | if (low[x] > disc[cur]) { 28 | bridges.push_back({cur, x}); 29 | } 30 | 31 | // articulation points 32 | if (par != 0 && low[x] >= disc[cur]) { 33 | arti_points.insert(cur); 34 | } 35 | 36 | } 37 | else if (x != par) { 38 | // backedge 39 | low[cur] = min(low[cur], disc[x]); 40 | } 41 | } 42 | 43 | // root is an arti or not 44 | if (par == 0 && child > 1) { 45 | arti_points.insert(cur); 46 | } 47 | 48 | return; 49 | } 50 | 51 | 52 | int main() 53 | { 54 | freopen("input.txt", "r", stdin); 55 | freopen("output.txt", "w", stdout); 56 | 57 | int n, m; 58 | cin >> n >> m; 59 | 60 | for (int i = 0; i < m; i++) { 61 | int x, y; 62 | cin >> x >> y; 63 | gr[x].push_back(y); 64 | gr[y].push_back(x); 65 | } 66 | 67 | dfs(1, 0); 68 | 69 | for (auto x : arti_points) cout << x << '\n'; 70 | 71 | for (auto x : bridges) { 72 | cout << x.first << " " << x.second << '\n'; 73 | } 74 | 75 | return 0; 76 | } -------------------------------------------------------------------------------- /Graphs C++/14 - Strongly Connected Components/kosaraju algorithm for SCC.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N], grr[N]; 8 | int vis[N], col[N]; 9 | vector order; 10 | 11 | vector components[N]; 12 | 13 | // topological sorting 14 | void dfs1(int cur) { 15 | vis[cur] = 1; 16 | for (auto x : gr[cur]) { 17 | if (!vis[x]) dfs1(x); 18 | } 19 | order.push_back(cur); 20 | } 21 | 22 | void dfs2(int cur, int comp) { 23 | vis[cur] = 1; 24 | col[cur] = comp; 25 | components[comp].push_back(cur); 26 | for (auto x : grr[cur]) { 27 | if (!vis[x]) dfs2(x, comp); 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | freopen("input.txt", "r", stdin); 34 | freopen("output.txt", "w", stdout); 35 | 36 | int n, m; 37 | cin >> n >> m; 38 | 39 | for (int i = 0; i < m; i++) { 40 | int x, y; 41 | cin >> x >> y; 42 | gr[x].push_back(y); 43 | grr[y].push_back(x); 44 | } 45 | 46 | for (int i = 1; i <= n; i++) { 47 | if (!vis[i]) dfs1(i); 48 | } 49 | 50 | reverse(order.begin(), order.end()); 51 | memset(vis, 0, sizeof(vis)); 52 | 53 | int comp = 1; 54 | for (auto x : order) { 55 | // cout << x << " "; 56 | if (!vis[x]) dfs2(x, comp++); 57 | } 58 | 59 | for (int i = 1; i <= n; i++) { 60 | cout << i << " " << col[i] << '\n'; 61 | } 62 | 63 | cout << "Total strongly components are -> " << comp - 1 << '\n'; 64 | 65 | // complexity O(n+m) 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /Graphs C++/14 - Strongly Connected Components/topological Order.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5 + 1; 6 | 7 | vector gr[N]; 8 | vector order; 9 | int vis[N]; 10 | 11 | void dfs(int cur, int par) { 12 | vis[cur] = 1; 13 | for (auto x : gr[cur]) { 14 | if (!vis[x]) { 15 | dfs(x, cur); 16 | } 17 | } 18 | // I am here because I came back from the subtree 19 | order.push_back(cur); 20 | return; 21 | } 22 | 23 | 24 | int main() 25 | { 26 | freopen("input.txt", "r", stdin); 27 | freopen("output.txt", "w", stdout); 28 | 29 | int n, m; 30 | cin >> n >> m; 31 | for (int i = 0; i < m; i++) { 32 | int x, y; 33 | cin >> x >> y; 34 | gr[x].push_back(y); 35 | } 36 | 37 | for (int i = 1; i <= n; i++) { 38 | if (!vis[i]) dfs(i, 0); 39 | } 40 | 41 | reverse(order.begin(), order.end()); 42 | 43 | for (auto x : order) cout << x << " "; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Graphs C++/15 - Trees/ancestor printing .cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N]; 8 | int Par[N]; 9 | 10 | void dfs(int cur, int par) { 11 | Par[cur] = par; 12 | for (auto x : gr[cur]) { 13 | if (x != par) { 14 | // x is child node 15 | dfs(x, cur); 16 | } 17 | } 18 | } 19 | 20 | int main() 21 | { 22 | freopen("input.txt", "r", stdin); 23 | freopen("output.txt", "w", stdout); 24 | 25 | int n; 26 | cin >> n; 27 | for (int i = 0; i < n - 1; i++) { 28 | int x, y; 29 | cin >> x >> y; 30 | gr[x].push_back(y); 31 | gr[y].push_back(x); 32 | } 33 | 34 | dfs(10, 0); 35 | 36 | int x = 6; 37 | // print all ancestors of 5 38 | 39 | while (x) { 40 | cout << x << '\n'; 41 | x = Par[x]; 42 | } 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Graphs C++/16 - Euler Tour/best euler tour.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N]; 8 | int tin[N], tout[N], tme = 0; 9 | int flat[N]; 10 | 11 | void dfs1(int cur, int par) { 12 | tin[cur] = tme++; 13 | for (auto x : gr[cur]) { 14 | if (x != par) { 15 | // x is child node 16 | dfs1(x, cur); 17 | } 18 | } 19 | tout[cur] = tme++; 20 | } 21 | 22 | void dfs2(int cur, int par) { 23 | cout << cur << " "; 24 | for (auto x : gr[cur]) { 25 | if (x != par) { 26 | // x is child node 27 | dfs2(x, cur); 28 | cout << cur << " "; 29 | } 30 | } 31 | } 32 | 33 | void dfs3(int cur, int par) { 34 | tin[cur] = ++tme; 35 | for (auto x : gr[cur]) { 36 | if (x != par) { 37 | // x is child node 38 | dfs3(x, cur); 39 | } 40 | } 41 | tout[cur] = tme; 42 | } 43 | 44 | int main() 45 | { 46 | freopen("input.txt", "r", stdin); 47 | freopen("output.txt", "w", stdout); 48 | 49 | int n; 50 | cin >> n; 51 | for (int i = 0; i < n - 1; i++) { 52 | int x, y; 53 | cin >> x >> y; 54 | gr[x].push_back(y); 55 | gr[y].push_back(x); 56 | } 57 | 58 | // tme = 1; 59 | // dfs1(1, 0); 60 | 61 | 62 | // dfs2(1, 0); 63 | 64 | tme = 0; 65 | dfs3(1, 0); 66 | 67 | for (int i = 1; i <= n; i++) { 68 | cout << i << " " << tin[i] << " " << tout[i] << '\n'; 69 | } 70 | 71 | for (int i = 1; i <= n; i++) { 72 | flat[tin[i]] = i; 73 | } 74 | 75 | for (int i = 1; i <= n; i++) { 76 | cout << flat[i] << " "; 77 | } 78 | 79 | return 0; 80 | } -------------------------------------------------------------------------------- /Graphs C++/16 - Euler Tour/euler tours.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N]; 8 | 9 | void dfs1(int cur, int par) { 10 | // time in 11 | cout << cur << " "; 12 | for (auto x : gr[cur]) { 13 | if (x != par) { 14 | // x is child node 15 | dfs1(x, cur); 16 | } 17 | } 18 | // time out 19 | cout << cur << " "; 20 | } 21 | 22 | void dfs2(int cur, int par) { 23 | cout << cur << " "; 24 | for (auto x : gr[cur]) { 25 | if (x != par) { 26 | // x is child node 27 | dfs2(x, cur); 28 | cout << cur << " "; 29 | } 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | freopen("input.txt", "r", stdin); 36 | freopen("output.txt", "w", stdout); 37 | 38 | int n; 39 | cin >> n; 40 | for (int i = 0; i < n - 1; i++) { 41 | int x, y; 42 | cin >> x >> y; 43 | gr[x].push_back(y); 44 | gr[y].push_back(x); 45 | } 46 | 47 | // dfs1(1, 0); 48 | 49 | dfs2(1, 0); 50 | 51 | 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /Graphs C++/17 - LCA/LCA using 2 pointers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5; 6 | 7 | vector gr[N]; 8 | int dep[N], Par[N]; 9 | 10 | void dfs(int cur, int par) { 11 | Par[cur] = par; 12 | dep[cur] = dep[par] + 1; 13 | for (auto x : gr[cur]) { 14 | if (x != par) { 15 | dfs(x, cur); 16 | } 17 | } 18 | } 19 | 20 | int LCA(int u, int v) { 21 | if (u == v) return u; 22 | 23 | if (dep[u] < dep[v]) swap(u, v); 24 | // depth of u is more than depth of v 25 | 26 | int diff = dep[u] - dep[v]; 27 | 28 | // depth of both nodes same 29 | while (diff--) { 30 | u = Par[u]; 31 | } 32 | 33 | // until they are equal nodes keep climbing 34 | while (u != v) { 35 | u = Par[u]; 36 | v = Par[v]; 37 | } 38 | 39 | return u; 40 | } 41 | 42 | int main() 43 | { 44 | freopen("input.txt", "r", stdin); 45 | freopen("output.txt", "w", stdout); 46 | 47 | int n; 48 | cin >> n; 49 | 50 | for (int i = 1; i < n; i++) { 51 | int x, y; 52 | cin >> x >> y; 53 | gr[x].push_back(y); 54 | gr[y].push_back(x); 55 | } 56 | 57 | dfs(1, 0); 58 | 59 | // for (int i = 1; i <= n; i++) { 60 | // cout << i << " " << dep[i] << '\n'; 61 | // } 62 | 63 | cout << LCA(9, 12) << '\n'; 64 | cout << LCA(10, 8) << '\n'; 65 | cout << LCA(9, 11) << '\n'; 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /Graphs C++/17 - LCA/LCA using sparse table.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5, M = 20; 6 | 7 | vector gr[N]; 8 | int dep[N], Par[N][M]; 9 | 10 | // O(N*M) 11 | void dfs(int cur, int par) { 12 | dep[cur] = dep[par] + 1; 13 | 14 | Par[cur][0] = par; 15 | for (int j = 1; j < M; j++) { 16 | Par[cur][j] = Par[Par[cur][j - 1]][j - 1]; 17 | } 18 | 19 | for (auto x : gr[cur]) { 20 | if (x != par) { 21 | dfs(x, cur); 22 | } 23 | } 24 | } 25 | 26 | // O(M) = logN 27 | int LCA(int u, int v) { 28 | if (u == v) return u; 29 | if (dep[u] < dep[v]) swap(u, v); 30 | int diff = dep[u] - dep[v]; 31 | for (int j = M - 1; j >= 0; j--) { 32 | if ((diff >> j) & 1) { 33 | // jth bit of diff is set 34 | u = Par[u][j]; 35 | } 36 | } 37 | // u and v are on the same level 38 | for (int j = M - 1; j >= 0; j--) { 39 | if (Par[u][j] != Par[v][j]) { 40 | u = Par[u][j]; 41 | v = Par[v][j]; 42 | } 43 | } 44 | 45 | // Par[v][0] 46 | return Par[u][0]; 47 | } 48 | 49 | // O(1) 50 | int LengthFromUtoV(int u, int v) { 51 | int lca = LCA(u, v); 52 | return dep[u] + dep[v] - 2 * dep[lca]; 53 | } 54 | 55 | int main() 56 | { 57 | freopen("input.txt", "r", stdin); 58 | freopen("output.txt", "w", stdout); 59 | 60 | int n; 61 | cin >> n; 62 | 63 | for (int i = 1; i < n; i++) { 64 | int x, y; 65 | cin >> x >> y; 66 | gr[x].push_back(y); 67 | gr[y].push_back(x); 68 | } 69 | 70 | dfs(1, 0); 71 | 72 | // for (int i = 1; i <= 12; i++) { 73 | // cout << i << "-> "; 74 | // for (int j = 0; j < 4; j++) { 75 | // cout << Par[i][j] << " "; 76 | // } cout << '\n'; 77 | // } 78 | 79 | // for (int i = 1; i <= n; i++) { 80 | // cout << i << " " << dep[i] << '\n'; 81 | // } 82 | 83 | // cout << LCA(9, 12) << '\n'; 84 | // cout << LCA(10, 8) << '\n'; 85 | // cout << LCA(9, 11) << '\n'; 86 | 87 | cout << LengthFromUtoV(9, 12) << '\n'; 88 | cout << LengthFromUtoV(10, 8) << '\n'; 89 | 90 | return 0; 91 | } -------------------------------------------------------------------------------- /Graphs C++/18 - Re rooting of. trees/Re-rooting brrute force.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5, M = 20; 6 | 7 | vector gr[N]; 8 | int sub[N]; 9 | 10 | // sum of subtree sizes of all the nodes 11 | int dfs(int cur, int par) { 12 | sub[cur] = 1; 13 | 14 | int sum = 0; 15 | 16 | for (auto x : gr[cur]) { 17 | if (x != par) { 18 | 19 | sum += dfs(x, cur); 20 | sub[cur] += sub[x]; 21 | 22 | } 23 | } 24 | 25 | sum += sub[cur]; 26 | 27 | return sum; 28 | } 29 | 30 | int main() 31 | { 32 | freopen("input.txt", "r", stdin); 33 | freopen("output.txt", "w", stdout); 34 | 35 | int n; 36 | cin >> n; 37 | 38 | for (int i = 1; i < n; i++) { 39 | int x, y; 40 | cin >> x >> y; 41 | gr[x].push_back(y); 42 | gr[y].push_back(x); 43 | } 44 | 45 | int ans = 0; 46 | for (int i = 1; i <= n; i++) { 47 | ans = max(ans, dfs(i, 0)); 48 | } 49 | 50 | // cout << dfs(3, 0) << '\n'; 51 | // O(n*n) 52 | 53 | cout << ans; 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /Graphs C++/18 - Re rooting of. trees/re rooting .cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 1e5, M = 20; 6 | 7 | vector gr[N]; 8 | int sub[N], dp[N]; 9 | 10 | // sum of subtree sizes of all the nodes 11 | void dfs(int cur, int par) { 12 | sub[cur] = 1; 13 | dp[cur] = 0; 14 | 15 | for (auto x : gr[cur]) { 16 | if (x != par) { 17 | dfs(x, cur); 18 | dp[cur] += dp[x]; 19 | sub[cur] += sub[x]; 20 | } 21 | } 22 | 23 | dp[cur] += sub[cur]; 24 | return ; 25 | } 26 | 27 | int ans = 0; 28 | 29 | void dfs1(int cur, int par) { 30 | // dp values are according to as cur is the root of the tree 31 | cout << cur << " " << dp[cur] << '\n'; 32 | ans = max(ans, dp[cur]); 33 | 34 | for (auto x : gr[cur]) { 35 | if (x != par) { 36 | // remove x from subtree of cur 37 | dp[cur] -= dp[x]; 38 | dp[cur] -= sub[x]; 39 | sub[cur] -= sub[x]; 40 | // now add cur as the subtree of x 41 | sub[x] += sub[cur]; 42 | dp[x] += dp[cur]; 43 | dp[x] += sub[cur]; 44 | 45 | dfs1(x, cur); 46 | 47 | // come back from x 48 | // rollback the changes as original tree 49 | dp[x] -= sub[cur]; 50 | dp[x] -= dp[cur]; 51 | sub[x] -= sub[cur]; 52 | sub[cur] += sub[x]; 53 | dp[cur] += sub[x]; 54 | dp[cur] += dp[x]; 55 | 56 | } 57 | } 58 | 59 | } 60 | 61 | int main() 62 | { 63 | freopen("input.txt", "r", stdin); 64 | freopen("output.txt", "w", stdout); 65 | 66 | int n; 67 | cin >> n; 68 | 69 | for (int i = 1; i < n; i++) { 70 | int x, y; 71 | cin >> x >> y; 72 | gr[x].push_back(y); 73 | gr[y].push_back(x); 74 | } 75 | 76 | dfs(1, 0); 77 | 78 | // for (int i = 1; i <= n; i++) { 79 | // cout << dp[i] << " " << sub[i] << '\n'; 80 | // } 81 | 82 | dfs1(1, 0); 83 | 84 | cout << ans << '\n'; 85 | 86 | return 0; 87 | } -------------------------------------------------------------------------------- /Graphs C++/19 - Network Flow/dinic's algprithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct Dinic { 6 | // from x to y with residual capacity 7 | struct edge { 8 | int x, y, w; 9 | }; 10 | 11 | vector> gr; 12 | vector edges; 13 | vector level; 14 | vector edge_sz; 15 | 16 | int n, source, sink, ec = 0; 17 | Dinic(int n, int source, int sink) { 18 | this->n = n; 19 | this->source = source; 20 | this->sink = sink; 21 | gr.resize(n); 22 | edge_sz.resize(n); 23 | } 24 | 25 | void add_edge(int x, int y, int w) { 26 | edges.push_back({x, y, w}); 27 | gr[x].push_back(ec++); 28 | edges.push_back({y, x, 0}); 29 | gr[y].push_back(ec++); 30 | } 31 | 32 | bool level_graph() { 33 | level.clear(); level.resize(n, -1); 34 | 35 | queue Q; 36 | Q.push(source); 37 | level[source] = -1; 38 | 39 | while (!Q.empty()) { 40 | int cur = Q.front(); 41 | Q.pop(); 42 | 43 | for (auto xx : gr[cur]) { 44 | int to = edges[xx].y; 45 | int w = edges[xx].w; 46 | 47 | if (w && level[to] == -1) { 48 | level[to] = level[cur] + 1; 49 | Q.push(to); 50 | } 51 | 52 | } 53 | } 54 | 55 | return level[sink] != -1; 56 | } 57 | 58 | int augment(int cur, int flow) { 59 | if (cur == sink) return flow; 60 | 61 | for (int &i = edge_sz[cur]; i >= 0; i--) { 62 | int edge_index = gr[cur][i]; 63 | int w = edges[edge_index].w; 64 | int y = edges[edge_index].y; 65 | 66 | if (w && level[y] == level[cur] + 1) { 67 | int bottleneck_flow = augment(y, min(w, flow)); 68 | 69 | if (bottleneck_flow) { 70 | // forward edge according to current augmented path 71 | edges[edge_index].w -= bottleneck_flow; 72 | // backward edge 73 | edges[edge_index ^ 1].w += bottleneck_flow; 74 | 75 | return bottleneck_flow; 76 | } 77 | 78 | } 79 | } 80 | return 0; 81 | } 82 | 83 | int max_flow() { 84 | int total_flow = 0; 85 | 86 | while (level_graph()) { 87 | // find augmenting paths and update in residual network 88 | for (int i = 0; i < n; i++) edge_sz[i] = gr[i].size() - 1; 89 | while (int flow = augment(0, 1e9)) { 90 | total_flow += flow; 91 | } 92 | } 93 | 94 | return total_flow; 95 | } 96 | 97 | }; 98 | 99 | int main() 100 | { 101 | freopen("input.txt", "r", stdin); 102 | freopen("output.txt", "w", stdout); 103 | 104 | Dinic G(4, 0, 3); 105 | 106 | G.add_edge(0, 1, 5); 107 | G.add_edge(1, 2, 10); 108 | G.add_edge(2, 3, 3); 109 | 110 | cout << G.max_flow(); 111 | 112 | return 0; 113 | } -------------------------------------------------------------------------------- /Graphs C++/20 - Bonus/board-game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | #define M 3 7 | #define N 4 8 | 9 | 10 | class Node{ 11 | public: 12 | char s; 13 | unordered_map children; 14 | string word; 15 | bool isTerminal; 16 | 17 | Node(char s){ 18 | this->s = s; 19 | isTerminal = false; 20 | word = ""; 21 | } 22 | }; 23 | 24 | class Trie{ 25 | public: 26 | Node*root; 27 | 28 | Trie(){ 29 | root = new Node('\0'); 30 | } 31 | 32 | void addWord(string word){ 33 | 34 | Node * temp = root; 35 | for(auto ch : word){ 36 | if(temp->children.count(ch)==0){ 37 | temp->children[ch] = new Node(ch); 38 | } 39 | temp = temp->children[ch]; 40 | } 41 | //last node 42 | temp->isTerminal = true; 43 | temp->word = word; 44 | } 45 | }; 46 | 47 | 48 | //main algorithm (8-way dfs + trie guided search) 49 | 50 | void dfs(char board[M][N],Node *node,int i,int j,bool visited[][N], unordered_set &output){ 51 | 52 | //base case 53 | char ch = board[i][j]; 54 | if(node->children.count(ch)==0){ 55 | return; 56 | } 57 | 58 | //otherwise trie contains this node 59 | visited[i][j] = true; 60 | node = node->children[ch]; 61 | 62 | 63 | // if it is a terminal node in the trie 64 | if(node->isTerminal){ 65 | output.insert(node->word); 66 | } 67 | 68 | //explore the neigbours 69 | int dx[] = {0, 1 , 1 ,1, 0, -1, -1,-1}; 70 | int dy[] = {-1,-1, 0, 1, 1, 1, 0, -1}; 71 | 72 | for(int k=0;k<8;k++){ 73 | 74 | int ni = i + dx[k]; 75 | int nj = j + dy[k]; 76 | 77 | //if it is in bounds and is not visited 78 | if(ni>=0 and nj>=0 and ni < M and nj < N and !visited[ni][nj]){ 79 | dfs(board,node,ni,nj,visited,output); 80 | } 81 | } 82 | //last step (backtracking) 83 | visited[i][j] = false; 84 | return; 85 | } 86 | 87 | 88 | int main() { 89 | 90 | 91 | 92 | string words[] = {"SNAKE", "FOR", "QUEZ", "SNACK", "SNACKS", "GO","TUNES","CAT"}; 93 | 94 | char board[M][N] = { { 'S', 'E', 'R' ,'T'}, 95 | { 'U', 'N', 'K' ,'S'}, 96 | { 'T', 'C', 'A' ,'T'} }; 97 | 98 | //1. Trie 99 | 100 | Trie t; 101 | for(auto w : words){ 102 | t.addWord(w); 103 | } 104 | 105 | //2. Take a container to store words that are found in dfs search 106 | unordered_set output; 107 | 108 | 109 | //3. Step (8-DFS Search from every cell) 110 | bool visited[M][N] = {0}; 111 | 112 | 113 | for(int i=0; i 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /Graphs Java/.idea/libraries/KotlinJavaRuntime.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Graphs Java/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Graphs Java/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Graphs Java/Graphs.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Graphs Java/out/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/.DS_Store -------------------------------------------------------------------------------- /Graphs Java/out/production/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/.DS_Store -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/.DS_Store -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ArticulationPointAndBridges/ArticulationPointAndBridges$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ArticulationPointAndBridges/ArticulationPointAndBridges$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ArticulationPointAndBridges/ArticulationPointAndBridges.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ArticulationPointAndBridges/ArticulationPointAndBridges.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/Bonus/BoardGame$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/Bonus/BoardGame$Node.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/Bonus/BoardGame$Trie.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/Bonus/BoardGame$Trie.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/Bonus/BoardGame.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/Bonus/BoardGame.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/BreadthFirstSearch/Bfs$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/BreadthFirstSearch/Bfs$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/BreadthFirstSearch/Bfs.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/BreadthFirstSearch/Bfs.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/BreadthFirstSearch/BfsShortestPath$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/BreadthFirstSearch/BfsShortestPath$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/BreadthFirstSearch/BfsShortestPath.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/BreadthFirstSearch/BfsShortestPath.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/BreadthFirstSearch/Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/BreadthFirstSearch/Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/BreadthFirstSearch/snakesAndLadder$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/BreadthFirstSearch/snakesAndLadder$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/BreadthFirstSearch/snakesAndLadder.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/BreadthFirstSearch/snakesAndLadder.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/CycleDetection/Bipartite.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/CycleDetection/Bipartite.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/CycleDetection/CycleDetectionDirected$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/CycleDetection/CycleDetectionDirected$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/CycleDetection/CycleDetectionDirected.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/CycleDetection/CycleDetectionDirected.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/CycleDetection/CycleDetectionUndirected$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/CycleDetection/CycleDetectionUndirected$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/CycleDetection/CycleDetectionUndirected.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/CycleDetection/CycleDetectionUndirected.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DepthFirstSearch/LongestPathSequence.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DepthFirstSearch/LongestPathSequence.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DepthFirstSearch/dfs$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DepthFirstSearch/dfs$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DepthFirstSearch/dfs.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DepthFirstSearch/dfs.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DepthFirstSearch/largestIsland.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DepthFirstSearch/largestIsland.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DepthFirstSearch/largestIslandCopy.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DepthFirstSearch/largestIslandCopy.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DfsTreesAndBackEdges/CycleInGraph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DfsTreesAndBackEdges/CycleInGraph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DfsTreesAndBackEdges/DfsTreesAndBackEdges.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DfsTreesAndBackEdges/DfsTreesAndBackEdges.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DfsTreesAndBackEdges/DfsTreesAndBackEdgesDirected.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DfsTreesAndBackEdges/DfsTreesAndBackEdgesDirected.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalBFS$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalBFS$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalBFS.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalBFS.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalDFS$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalDFS$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalDFS.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalDFS.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalSort$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalSort$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalSort.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DirectedAcyclicGraph/topologicalSort.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_1$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_1$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_1$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_1$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_1.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_2$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_2$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_2$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_2$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSU_2.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSUrankPathCompression$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSUrankPathCompression$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSUrankPathCompression$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSUrankPathCompression$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/DisjointSetUnion/DSUrankPathCompression.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/DisjointSetUnion/DSUrankPathCompression.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/EulerTour/EulerTour.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/EulerTour/EulerTour.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/EulerTour/bestEulerTour.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/EulerTour/bestEulerTour.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/FloodFill/MakeLargestIsland.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/FloodFill/MakeLargestIsland.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/FloodFill/alphabetMatch.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/FloodFill/alphabetMatch.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/FloodFill/colorCount.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/FloodFill/colorCount.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/FloodFill/graphInput.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/FloodFill/graphInput.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/FloodFill/largestIsland.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/FloodFill/largestIsland.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/FloodFill/totalConnectedComponent.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/FloodFill/totalConnectedComponent.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_01$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_01$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_01.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_01.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02$Node.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02_node$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02_node$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02_node$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02_node$Node.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02_node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/GraphRepresentation/adj_list_02_node.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/LCA/_2Pointer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/LCA/_2Pointer.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/LCA/sparseTable.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/LCA/sparseTable.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/MinimumSpanningTree/Kruskal$DSU.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/MinimumSpanningTree/Kruskal$DSU.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/MinimumSpanningTree/Kruskal$Graph$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/MinimumSpanningTree/Kruskal$Graph$1.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/MinimumSpanningTree/Kruskal$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/MinimumSpanningTree/Kruskal$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/MinimumSpanningTree/Kruskal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/MinimumSpanningTree/Kruskal.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/MinimumSpanningTree/Prims$Graph$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/MinimumSpanningTree/Prims$Graph$1.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/MinimumSpanningTree/Prims$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/MinimumSpanningTree/Prims$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/MinimumSpanningTree/Prims$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/MinimumSpanningTree/Prims$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/MinimumSpanningTree/Prims.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/MinimumSpanningTree/Prims.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/NetworkFlow/dinicsAlgo$Dinic$edge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/NetworkFlow/dinicsAlgo$Dinic$edge.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/NetworkFlow/dinicsAlgo$Dinic.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/NetworkFlow/dinicsAlgo$Dinic.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/NetworkFlow/dinicsAlgo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/NetworkFlow/dinicsAlgo.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ReRooting/Rerooting.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ReRooting/Rerooting.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ReRooting/bruteForce.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ReRooting/bruteForce.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ShortestPath/Djikstra$Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ShortestPath/Djikstra$Graph.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ShortestPath/Djikstra$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ShortestPath/Djikstra$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ShortestPath/Djikstra.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ShortestPath/Djikstra.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ShortestPath/FloydWarshal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ShortestPath/FloydWarshal.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ShortestPath/ShortestPathGrid$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ShortestPath/ShortestPathGrid$Node.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ShortestPath/ShortestPathGrid.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ShortestPath/ShortestPathGrid.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/ShortestPath/bellmanFord.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/ShortestPath/bellmanFord.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/StronglyConnectedComponent/KosarajuAlgorithm.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/StronglyConnectedComponent/KosarajuAlgorithm.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/StronglyConnectedComponent/TopologicalOrder.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/StronglyConnectedComponent/TopologicalOrder.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/TravellingSalesMan/travellingSalesMan.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/TravellingSalesMan/travellingSalesMan.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/Trees/AncestorPrinting.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/Trees/AncestorPrinting.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/multiSourceBfs/BFSMinimumOperations$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/multiSourceBfs/BFSMinimumOperations$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/multiSourceBfs/BFSMinimumOperations.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/multiSourceBfs/BFSMinimumOperations.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/multiSourceBfs/MinimumDistance$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/multiSourceBfs/MinimumDistance$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/multiSourceBfs/MinimumDistance.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/multiSourceBfs/MinimumDistance.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/multiSourceBfs/ShortestPathFirstToLastRow$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/multiSourceBfs/ShortestPathFirstToLastRow$Pair.class -------------------------------------------------------------------------------- /Graphs Java/out/production/Graphs/multiSourceBfs/ShortestPathFirstToLastRow.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coding-minutes/graph-algorithms-for-competitive-coding/b790df992692006ffa83f967138626214de91e7b/Graphs Java/out/production/Graphs/multiSourceBfs/ShortestPathFirstToLastRow.class -------------------------------------------------------------------------------- /Graphs Java/src/ArticulationPointAndBridges/ArticulationPointAndBridges.java: -------------------------------------------------------------------------------- 1 | package ArticulationPointAndBridges; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | import java.util.Scanner; 6 | import java.util.Set; 7 | 8 | public class ArticulationPointAndBridges { 9 | 10 | static class Pair{ 11 | int first, second; 12 | 13 | Pair(int a, int b){ 14 | first = a; 15 | second = b; 16 | } 17 | } 18 | 19 | static final int N = (int) (1e5 + 1); 20 | 21 | static ArrayList[] gr = new ArrayList[N]; 22 | static Set arti_points = new HashSet<>(); 23 | static { 24 | for(int i = 0 ; i < N ; i++){ 25 | gr[i] = new ArrayList<>(); 26 | } 27 | } 28 | 29 | static int tme = 1; 30 | static boolean[] vis = new boolean[N]; 31 | static int[] disc = new int[N]; 32 | static int[] low = new int[N]; 33 | 34 | static ArrayList bridges = new ArrayList<>(); 35 | 36 | static void dfs(int cur, int par) { 37 | vis[cur] = true; 38 | disc[cur] = low[cur] = tme++; 39 | int child = 0; 40 | for (int x : gr[cur]) { 41 | 42 | if (!vis[x]) { 43 | dfs(x, cur); 44 | child++; 45 | // we know low and disc of x 46 | low[cur] = Math.min(low[cur], low[x]); 47 | 48 | // bridges 49 | if (low[x] > disc[cur]) { 50 | bridges.add(new Pair(cur, x)); 51 | } 52 | 53 | // articulation points 54 | if (par != 0 && low[x] >= disc[cur]) { 55 | arti_points.add(cur); 56 | } 57 | 58 | } 59 | else if (x != par) { 60 | // backedge 61 | low[cur] = Math.min(low[cur], disc[x]); 62 | } 63 | } 64 | 65 | // root is an arti or not 66 | if (par == 0 && child > 1) { 67 | arti_points.add(cur); 68 | } 69 | 70 | } 71 | 72 | 73 | public static void main(String[] args) 74 | { 75 | Scanner scn = new Scanner(System.in); 76 | int n = scn.nextInt(), m = scn.nextInt(); 77 | 78 | for (int i = 0; i < m; i++) { 79 | int x = scn.nextInt(), y = scn.nextInt(); 80 | gr[x].add(y); 81 | gr[y].add(x); 82 | 83 | } 84 | 85 | dfs(1, 0); 86 | 87 | for (int x : arti_points) System.out.println(x); 88 | 89 | for (Pair x : bridges) { 90 | System.out.println( x.first + " " + x.second ); 91 | } 92 | 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Graphs Java/src/BreadthFirstSearch/Bfs.java: -------------------------------------------------------------------------------- 1 | package BreadthFirstSearch; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.LinkedList; 7 | import java.util.Queue; 8 | 9 | public class Bfs { 10 | 11 | 12 | static class Graph{ 13 | int V; 14 | ArrayList[] list; 15 | 16 | public Graph(int v){ 17 | V = v; 18 | list = new ArrayList[v]; 19 | for(int i = 0; i < v; i++){ 20 | list[i] = new ArrayList<>(); 21 | } 22 | } 23 | 24 | void addEdge(int i, int j, boolean unDirected){ 25 | list[i].add(j); 26 | if(unDirected) 27 | list[j].add(i); 28 | } 29 | 30 | void bfs(int source){ 31 | 32 | Queue q = new LinkedList<>(); 33 | Boolean[] visited = new Boolean[V]; 34 | Arrays.fill(visited, false); 35 | 36 | q.add(source); 37 | visited[source] = true; 38 | 39 | while(!q.isEmpty()){ 40 | //Do some work for every node 41 | int f = q.poll(); 42 | System.out.println(f); 43 | // q.pop(); 44 | 45 | //PUsh the nbrs of current node inside q if they are not already visited 46 | for(int nbr : list[f]){ 47 | if(!visited[nbr]){ 48 | q.add(nbr); 49 | visited[nbr] = true; 50 | } 51 | } 52 | } 53 | } 54 | 55 | 56 | } 57 | 58 | public static void main(String[] args){ 59 | Graph g = new Graph(7); 60 | g.addEdge(0,1, true); 61 | g.addEdge(1,2, true); 62 | g.addEdge(2,3, true); 63 | g.addEdge(3,5, true); 64 | g.addEdge(5,6, true); 65 | g.addEdge(4,5, true); 66 | g.addEdge(0,4, true); 67 | g.addEdge(3,4, true); 68 | g.bfs(1); 69 | 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Graphs Java/src/BreadthFirstSearch/BfsShortestPath.java: -------------------------------------------------------------------------------- 1 | package BreadthFirstSearch; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | public class BfsShortestPath { 9 | 10 | static class Graph{ 11 | int V; 12 | ArrayList[] list; 13 | 14 | public Graph(int v){ 15 | V = v; 16 | list = new ArrayList[v]; 17 | for(int i = 0; i < v; i++){ 18 | list[i] = new ArrayList<>(); 19 | } 20 | } 21 | 22 | void addEdge(int i, int j, boolean unDirected){ 23 | list[i].add(j); 24 | if(unDirected) 25 | list[j].add(i); 26 | } 27 | 28 | void bfs(int source,int dest){ 29 | 30 | Queue q = new LinkedList<>(); 31 | boolean[] visited = new boolean[V]; 32 | Arrays.fill(visited, false); 33 | 34 | int[] dist = new int[V]; 35 | int[] parent = new int[V]; 36 | 37 | for(int i=0;i[] list; 35 | 36 | public Graph(int v){ 37 | V = v; 38 | list = new ArrayList[v]; 39 | for(int i = 0; i < v; i++){ 40 | list[i] = new ArrayList<>(); 41 | } 42 | } 43 | 44 | void addEdge(int i, int j){ 45 | list[i].add(j); 46 | } 47 | 48 | int minCostBFS(int src, int dest){ 49 | Queue q = new LinkedList<>(); 50 | boolean[] visited = new boolean[V]; 51 | int[] dist = new int[V]; 52 | Arrays.fill(visited, false); 53 | 54 | q.add(src); 55 | visited[src] = true; 56 | dist[src] = 0; 57 | 58 | while(!q.isEmpty()){ 59 | int f = q.poll(); 60 | 61 | for(int nbr : list[f]){ 62 | if(!visited[nbr]){ 63 | q.add(nbr); 64 | visited[nbr] = true; 65 | dist[nbr] = dist[f] + 1; 66 | } 67 | } 68 | } 69 | return dist[dest]; 70 | } 71 | 72 | 73 | } 74 | 75 | public static int min_dice_throws(int n, ArrayList snakes, ArrayList ladders){ 76 | int[] board = new int[n+1]; 77 | 78 | //board to graph conversion 79 | for(Pair sp: snakes){ 80 | int s = sp.getFirst(); 81 | int e = sp.getSecond(); 82 | board[s] = e - s; 83 | } 84 | 85 | for(Pair lp: ladders){ 86 | int s = lp.getFirst(); 87 | int e = lp.getSecond(); 88 | board[s] = e - s; 89 | } 90 | 91 | //Graph 92 | Graph g = new Graph(n+1); 93 | for(int u=1;u[] graph, int node, int[] visited, int parent, int color){ 9 | //come to node 10 | visited[node] = color; //1 or 2, both mean visited 11 | 12 | for(int nbr : graph[node]){ 13 | 14 | if(visited[nbr]==0){ 15 | boolean subProb = dfs_helper(graph,nbr,visited,node,3-color); 16 | 17 | if(!subProb){ 18 | return false; 19 | } 20 | 21 | } 22 | else if(nbr!=parent && color==visited[nbr]){ 23 | return false; 24 | } 25 | 26 | } 27 | return true; 28 | } 29 | 30 | 31 | static boolean dfs(ArrayList[] graph, int N){ 32 | 33 | int[] visited = new int[N]; // 0- Not Visited, 1 - Visited Color is 1, 2 - Visted Color 2 34 | 35 | int color = 1; 36 | boolean ans = dfs_helper(graph,0,visited,-1,color); 37 | //later one 38 | 39 | //colors 40 | for(int i=0;i[] graph = new ArrayList[N]; 53 | for(int i = 0; i < N; i++){ 54 | graph[i] = new ArrayList<>(); 55 | } 56 | 57 | while(M-- > 0){ 58 | int x = scn.nextInt(), y = scn.nextInt(); 59 | 60 | graph[x].add(y); 61 | graph[y].add(x); 62 | 63 | } 64 | 65 | //BFS or DFS, by coloring the nodes at each step (current node has color 1, nbr should have a color 2) 66 | if(dfs(graph,N)){ 67 | System.out.println("Yes its bipartite"); 68 | } 69 | else{ 70 | System.out.println("Not bipartite"); 71 | } 72 | 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Graphs Java/src/CycleDetection/CycleDetectionDirected.java: -------------------------------------------------------------------------------- 1 | package CycleDetection; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class CycleDetectionDirected { 6 | 7 | static class Graph { 8 | int V; 9 | ArrayList[] list; 10 | 11 | public Graph(int v) { 12 | V = v; 13 | list = new ArrayList[v]; 14 | for (int i = 0; i < v; i++) { 15 | list[i] = new ArrayList<>(); 16 | } 17 | } 18 | 19 | void addEdge(int i, int j) { 20 | list[i].add(j); 21 | } 22 | 23 | boolean dfs(int node,boolean[] visited, boolean[] stack){ 24 | //arrive at node 25 | visited[node] = true; 26 | stack[node] = true; 27 | 28 | //do some work at node,return true if backedge is found here itself 29 | for(int nbr : list[node]){ 30 | 31 | if(stack[nbr]){ 32 | return true; 33 | } 34 | else if(!visited[nbr]){ 35 | boolean nbrFoundACycle = dfs(nbr,visited,stack); 36 | if(nbrFoundACycle){ 37 | return true; 38 | } 39 | } 40 | } 41 | 42 | //going back 43 | stack[node] = false; 44 | return false; 45 | } 46 | 47 | boolean contains_cycle(){ 48 | boolean[] visited = new boolean[V]; 49 | boolean[] stack = new boolean[V]; 50 | 51 | for(int i=0;i[] list; 10 | 11 | public Graph(int v) { 12 | V = v; 13 | list = new ArrayList[v]; 14 | for (int i = 0; i < v; i++) { 15 | list[i] = new ArrayList<>(); 16 | } 17 | } 18 | 19 | void addEdge(int i, int j) { 20 | list[i].add(j); 21 | list[j].add(i); 22 | } 23 | 24 | boolean dfs(int node, boolean[] visited, int parent){ 25 | //mark that node visited 26 | visited[node] = true; 27 | 28 | for(int nbr : list[node]){ 29 | 30 | if(!visited[nbr]){ 31 | 32 | boolean nbrFoundACycle = dfs(nbr,visited,node); 33 | if(nbrFoundACycle){ 34 | return true; 35 | } 36 | } 37 | //nbr is visited and its not the parent of current node in the current dfs call 38 | else if(nbr!=parent){ 39 | return true; 40 | } 41 | } 42 | return false; 43 | } 44 | 45 | boolean contains_cycle(){ 46 | //Graph is single component 47 | boolean[] visited = new boolean[V]; 48 | return dfs(0, visited, -1); 49 | } 50 | 51 | } 52 | 53 | public static void main(String[] args){ 54 | 55 | Graph g = new Graph(3); 56 | // g.addEdge(0,1); 57 | g.addEdge(2,0); 58 | g.addEdge(2,0); 59 | 60 | System.out.println(g.contains_cycle()); 61 | 62 | } 63 | 64 | } 65 | 66 | -------------------------------------------------------------------------------- /Graphs Java/src/DepthFirstSearch/LongestPathSequence.java: -------------------------------------------------------------------------------- 1 | package DepthFirstSearch; 2 | 3 | public class LongestPathSequence { 4 | static void dfs(int[][] matrix,boolean[][] visited, int[][] cache, int i,int j,int m,int n){ 5 | 6 | visited[i][j] = true; 7 | 8 | int dx[] = {-1,1,0,0}; 9 | int dy[] = {0,0,1,-1}; 10 | 11 | int cnt = 0; 12 | for(int k=0;k<4;k++){ 13 | int nx = i + dx[k]; 14 | int ny = j + dy[k]; 15 | 16 | if(nx>=0 && ny>=0 && nxmatrix[i][j]){ 17 | if(visited[nx][ny]){ 18 | cnt = Math.max(cnt,1+cache[nx][ny]); 19 | } 20 | else{ 21 | dfs(matrix,visited,cache,nx,ny,m,n); 22 | cnt = Math.max(cnt,1+cache[nx][ny]); 23 | } 24 | } 25 | } 26 | cache[i][j] = cnt; 27 | return; 28 | } 29 | 30 | static int longestPathSequence(int[][] matrix) { 31 | // Write your code here. 32 | int m = matrix.length; 33 | int n = matrix[0].length; 34 | boolean[][] visited = new boolean[m+1][n+1]; 35 | int[][] cache = new int[m+1][n+1]; 36 | //do a dfs from every cell //and store the length of of maximum len seq starting from that cell 37 | int ans = 0; 38 | for(int i=0;i[] list; 14 | 15 | public Graph(int v){ 16 | V = v; 17 | list = new ArrayList[v]; 18 | for(int i = 0; i < v; i++){ 19 | list[i] = new ArrayList<>(); 20 | } 21 | } 22 | 23 | void addEdge(int i, int j, boolean unDirected){ 24 | list[i].add(j); 25 | if(unDirected) 26 | list[j].add(i); 27 | } 28 | 29 | private void dfsHelper(int source, boolean[] visited){ 30 | visited[source] = true; 31 | System.out.print(source + " "); 32 | 33 | for(int nbr: list[source]){ 34 | if(!visited[nbr]){ 35 | dfsHelper(nbr, visited); 36 | } 37 | } 38 | } 39 | 40 | void dfs(int source){ 41 | boolean[] visited = new boolean[V]; 42 | Arrays.fill(visited, false); 43 | dfsHelper(source, visited); 44 | } 45 | 46 | 47 | } 48 | 49 | public static void main(String[] args){ 50 | 51 | Graph g = new Graph(7); 52 | g.addEdge(0,1, true); 53 | g.addEdge(1,2, true); 54 | g.addEdge(2,3, true); 55 | g.addEdge(3,5, true); 56 | g.addEdge(5,6, true); 57 | g.addEdge(4,5, true); 58 | g.addEdge(0,4, true); 59 | g.addEdge(3,4, true); 60 | g.dfs(1); 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Graphs Java/src/DepthFirstSearch/largestIsland.java: -------------------------------------------------------------------------------- 1 | package DepthFirstSearch; 2 | 3 | 4 | import java.util.Arrays; 5 | 6 | public class largestIsland { 7 | 8 | static int dfs(int[][] matrix, boolean[][] visited, int i,int j,int m,int n){ 9 | 10 | visited[i][j] = true; 11 | 12 | int cs = 1; 13 | 14 | int dx[] = {1,-1,0,0}; 15 | int dy[] = {0,0,1,-1}; 16 | 17 | for(int k=0;k<4;k++){ 18 | int nx = i + dx[k]; 19 | int ny = j + dy[k]; 20 | 21 | if(nx>=0 && nx=0 && nylargest){ 48 | largest = size; 49 | } 50 | 51 | } 52 | 53 | } 54 | } 55 | return largest; 56 | } 57 | 58 | public static void main(String[] args){ 59 | 60 | int[][] grid = { 61 | {1, 0, 0, 1, 0}, 62 | {1, 0, 1, 0, 0}, 63 | {0, 0, 1, 0, 1}, 64 | {1, 0, 1, 1, 1}, 65 | {1, 0, 1, 1, 0} 66 | }; 67 | System.out.println(largest_island(grid)); 68 | 69 | } 70 | } 71 | 72 | -------------------------------------------------------------------------------- /Graphs Java/src/DepthFirstSearch/largestIslandCopy.java: -------------------------------------------------------------------------------- 1 | package DepthFirstSearch; 2 | 3 | 4 | public class largestIslandCopy { 5 | 6 | static int dfs(int[][] matrix, boolean[][] visited, int i,int j,int m,int n){ 7 | 8 | visited[i][j] = true; 9 | 10 | int cs = 1; 11 | 12 | int dx[] = {1,-1,0,0}; 13 | int dy[] = {0,0,1,-1}; 14 | 15 | for(int k=0;k<4;k++){ 16 | int nx = i + dx[k]; 17 | int ny = j + dy[k]; 18 | 19 | if(nx>=0 && nx=0 && nylargest){ 46 | largest = size; 47 | } 48 | 49 | } 50 | 51 | } 52 | } 53 | return largest; 54 | } 55 | 56 | public static void main(String[] args){ 57 | 58 | int[][] grid = { 59 | {1, 0, 0, 1, 0}, 60 | {1, 0, 1, 0, 0}, 61 | {0, 0, 1, 0, 1}, 62 | {1, 0, 1, 1, 1}, 63 | {1, 0, 1, 1, 0} 64 | }; 65 | System.out.println(largest_island(grid)); 66 | 67 | } 68 | } 69 | 70 | -------------------------------------------------------------------------------- /Graphs Java/src/DfsTreesAndBackEdges/CycleInGraph.java: -------------------------------------------------------------------------------- 1 | package DfsTreesAndBackEdges; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class CycleInGraph { 7 | 8 | 9 | static final int N = (int) (1e5 + 1); 10 | 11 | static ArrayList[] gr = new ArrayList[N]; 12 | static int[] vis = new int[N]; 13 | static int[] Par = new int[N]; 14 | 15 | static { 16 | for(int i = 0 ; i < N ; i++){ 17 | gr[i] = new ArrayList<>(); 18 | } 19 | } 20 | 21 | 22 | static boolean cycle = false; 23 | 24 | static void dfs(int cur, int par) { 25 | // visited and in call stack 26 | vis[cur] = 1; 27 | Par[cur] = par; 28 | for (int x : gr[cur]) { 29 | if (vis[x] == 0) { 30 | dfs(x, cur); 31 | } 32 | else if (x != par && vis[x] == 1) { 33 | // backedge 34 | cycle = true; 35 | 36 | int u = cur, v = x; 37 | 38 | while (u != v) { 39 | System.out.print(u + " "); 40 | u = Par[u]; 41 | } 42 | System.out.print(u + " "); 43 | System.exit(0); 44 | } 45 | } 46 | // visited and not in call stack 47 | vis[cur] = 2; 48 | return; 49 | } 50 | 51 | public static void main(String[] args) 52 | { 53 | Scanner scn = new Scanner(System.in); 54 | int n = scn.nextInt(), m = scn.nextInt(); 55 | 56 | for (int i = 0; i < m; i++) { 57 | int x = scn.nextInt(), y = scn.nextInt(); 58 | gr[x].add(y); 59 | gr[y].add(x); 60 | 61 | } 62 | 63 | for (int i = 1; i <= n; i++) { 64 | if (vis[i] == 0) { 65 | dfs(i, 0); 66 | } 67 | } 68 | 69 | if (cycle) { 70 | System.out.print("Yes cycle found"); 71 | } 72 | else { 73 | System.out.print("Not found"); 74 | } 75 | 76 | 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Graphs Java/src/DfsTreesAndBackEdges/DfsTreesAndBackEdges.java: -------------------------------------------------------------------------------- 1 | package DfsTreesAndBackEdges; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class DfsTreesAndBackEdges { 7 | 8 | 9 | static final int N = (int) (1e5 + 1); 10 | 11 | static ArrayList[] gr = new ArrayList[N]; 12 | static boolean[] vis = new boolean[N]; 13 | static boolean cycle = false; 14 | 15 | static { 16 | for(int i = 0; i < gr.length; i++){ 17 | gr[i] = new ArrayList<>(); 18 | } 19 | } 20 | 21 | static void dfs(int cur, int par) { 22 | vis[cur] = true; 23 | for (int x : gr[cur]) { 24 | if (!vis[x]) { 25 | dfs(x, cur); 26 | } 27 | else if (x != par) { 28 | cycle = true; 29 | } 30 | } 31 | } 32 | 33 | public static void main(String[] args) 34 | { 35 | 36 | Scanner scn = new Scanner(System.in); 37 | int n = scn.nextInt(), m = scn.nextInt(); 38 | 39 | for (int i = 0; i < m; i++) { 40 | int x = scn.nextInt(), y = scn.nextInt(); 41 | gr[x].add(y); 42 | gr[y].add(x); 43 | 44 | } 45 | 46 | for (int i = 1; i <= n; i++) { 47 | if (!vis[i]) { 48 | dfs(i, 0); 49 | } 50 | } 51 | 52 | if (cycle) { 53 | System.out.print("Yes cycle found"); 54 | } 55 | else { 56 | System.out.print("Not found"); 57 | } 58 | 59 | 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /Graphs Java/src/DfsTreesAndBackEdges/DfsTreesAndBackEdgesDirected.java: -------------------------------------------------------------------------------- 1 | package DfsTreesAndBackEdges; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class DfsTreesAndBackEdgesDirected { 7 | 8 | 9 | static final int N = (int) (1e5 + 1); 10 | 11 | static ArrayList[] gr = new ArrayList[N]; 12 | static int[] vis = new int[N]; 13 | static boolean cycle = false; 14 | 15 | static { 16 | for(int i = 0 ; i < N ; i++){ 17 | gr[i] = new ArrayList<>(); 18 | } 19 | } 20 | 21 | 22 | static void dfs(int cur, int par) { 23 | // visited and in call stack 24 | vis[cur] = 1; 25 | for (int x : gr[cur]) { 26 | if (vis[x] == 0) { 27 | dfs(x, cur); 28 | } 29 | else if (x != par && vis[x] == 1) { 30 | // backedge 31 | cycle = true; 32 | } 33 | } 34 | // visited and not in call stack 35 | vis[cur] = 2; 36 | return; 37 | } 38 | 39 | public static void main(String[] args) { 40 | Scanner scn = new Scanner(System.in); 41 | int n = scn.nextInt(), m = scn.nextInt(); 42 | 43 | for (int i = 0; i < m; i++) { 44 | int x = scn.nextInt(), y = scn.nextInt(); 45 | gr[x].add(y); 46 | gr[y].add(x); 47 | 48 | } 49 | 50 | for (int i = 1; i <= n; i++) { 51 | if (vis[i] == 0) { 52 | dfs(i, 0); 53 | } 54 | } 55 | 56 | if (cycle) { 57 | System.out.print("Yes cycle found"); 58 | } 59 | else { 60 | System.out.print("Not found"); 61 | } 62 | 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Graphs Java/src/DirectedAcyclicGraph/topologicalBFS.java: -------------------------------------------------------------------------------- 1 | package DirectedAcyclicGraph; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | 7 | public class topologicalBFS { 8 | 9 | static class Graph{ 10 | int V; 11 | ArrayList[] list; 12 | 13 | public Graph(int v){ 14 | V = v; 15 | list = new ArrayList[v]; 16 | for(int i = 0; i < v; i++){ 17 | list[i] = new ArrayList<>(); 18 | } 19 | } 20 | 21 | void addEdge(int i, int j){ 22 | list[i].add(j); 23 | } 24 | 25 | //Complete this method 26 | void topological_sort() { 27 | int[] indegree = new int[V]; 28 | 29 | //Iterate over all the edges to find the right indegree 30 | for(int i=0;i q = new LinkedList<>(); 39 | //init the q with nodes having 0 indegree 40 | for(int i=0;i[] list; 13 | 14 | public Graph(int v){ 15 | V = v; 16 | list = new ArrayList[v]; 17 | for(int i = 0; i < v; i++){ 18 | list[i] = new ArrayList<>(); 19 | } 20 | } 21 | 22 | void addEdge(int i, int j){ 23 | list[i].add(j); 24 | } 25 | 26 | void dfs(int node, boolean[] visited, ArrayList ordering){ 27 | 28 | visited[node] = true; 29 | 30 | for(int nbr : list[node]){ 31 | if(!visited[nbr]){ 32 | dfs(nbr,visited,ordering); 33 | } 34 | } 35 | //at this point 36 | ordering.add( node); 37 | } 38 | 39 | //Complete this method 40 | void dfs_topological_sort() { 41 | 42 | boolean[] visited = new boolean[V]; 43 | ArrayList ordering = new ArrayList<>(); 44 | 45 | //we call dfs from every node if it not visited 46 | for(int i=0;i[] list; 13 | 14 | public Graph(int v){ 15 | V = v; 16 | list = new ArrayList[v]; 17 | for(int i = 0; i < v; i++){ 18 | list[i] = new ArrayList<>(); 19 | } 20 | } 21 | 22 | void addEdge(int i, int j, boolean bidir){ 23 | list[i].add(j); 24 | if(bidir){ 25 | list[j].add(i); 26 | } 27 | } 28 | 29 | void bfs(int s){ 30 | Queue q = new LinkedList<>(); 31 | q.add(s); 32 | 33 | 34 | int[] dist = new int[V]; 35 | //Init all nodes with inf dist 36 | for(int i=0;i l; 20 | 21 | 22 | public Graph(int V){ 23 | this.V = V; 24 | this.l = new ArrayList<>(); 25 | } 26 | 27 | void addEdge(int u,int v){ 28 | l.add(new Pair(u,v)); 29 | } 30 | // Find 31 | int findSet(int i,int parent[]){ 32 | //base case 33 | if(parent[i]==-1){ 34 | return i; 35 | } 36 | 37 | return findSet(parent[i],parent); 38 | } 39 | 40 | 41 | //Union 42 | void union_set(int x,int y,int parent[]){ 43 | int s1 = findSet(x,parent); 44 | int s2 = findSet(y,parent); 45 | 46 | if(s1!=s2){ 47 | parent[s1] = s2; 48 | } 49 | } 50 | 51 | 52 | boolean contains_cycle(){ 53 | //DSU Logic to check if graph contains cycle or not 54 | int parent[] = new int[V]; 55 | for(int i=0;i l; 20 | 21 | 22 | public Graph(int V){ 23 | this.V = V; 24 | this.l = new ArrayList<>(); 25 | } 26 | 27 | void addEdge(int u,int v){ 28 | l.add(new Pair(u,v)); 29 | } 30 | // Find 31 | int findSet(int i,int parent[]){ 32 | //base case 33 | if(parent[i]==-1){ 34 | return i; 35 | } 36 | //path compression optimisation 37 | return parent[i] = findSet(parent[i],parent); 38 | } 39 | 40 | 41 | //Union 42 | void union_set(int x, int y, int[] parent, int[] rank){ 43 | int s1 = findSet(x,parent); 44 | int s2 = findSet(y,parent); 45 | 46 | if(s1!=s2){ 47 | if(rank[s1][] gr = new ArrayList[N]; 11 | 12 | static { 13 | for(int i = 0; i < N; i++){ 14 | gr[i] = new ArrayList<>(); 15 | } 16 | } 17 | 18 | 19 | static void dfs1(int cur, int par) { 20 | // time in 21 | System.out.print(cur + " "); 22 | for (int x : gr[cur]) { 23 | if (x != par) { 24 | // x is child node 25 | dfs1(x, cur); 26 | } 27 | } 28 | // time out 29 | System.out.print(cur + " "); 30 | } 31 | 32 | static void dfs2(int cur, int par) { 33 | System.out.print(cur + " "); 34 | for (int x : gr[cur]) { 35 | if (x != par) { 36 | // x is child node 37 | dfs2(x, cur); 38 | System.out.print(cur + " "); 39 | } 40 | } 41 | } 42 | 43 | public static void main(String[] args){ 44 | 45 | Scanner scn = new Scanner(System.in); 46 | int n = scn.nextInt(); 47 | for (int i = 0; i < n-1; i++) { 48 | int x = scn.nextInt(), y = scn.nextInt(); 49 | gr[x].add(y); 50 | gr[y].add(x); 51 | 52 | } 53 | 54 | 55 | // dfs1(1, 0); 56 | 57 | dfs2(1, 0); 58 | 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /Graphs Java/src/EulerTour/bestEulerTour.java: -------------------------------------------------------------------------------- 1 | package EulerTour; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class bestEulerTour { 7 | 8 | 9 | 10 | static final int N = (int) (1e5 + 1); 11 | 12 | static ArrayList[] gr = new ArrayList[N]; 13 | 14 | static { 15 | for(int i = 0; i < N; i++){ 16 | gr[i] = new ArrayList<>(); 17 | } 18 | } 19 | static int[] tin = new int[N]; 20 | static int[] tout = new int[N]; 21 | static int[] flat = new int[N]; 22 | static int tme = 0; 23 | 24 | static void dfs1(int cur, int par) { 25 | tin[cur] = tme++; 26 | for (int x : gr[cur]) { 27 | if (x != par) { 28 | // x is child node 29 | dfs1(x, cur); 30 | } 31 | } 32 | tout[cur] = tme++; 33 | } 34 | 35 | static void dfs2(int cur, int par) { 36 | System.out.println(cur + " "); 37 | for (int x : gr[cur]) { 38 | if (x != par) { 39 | // x is child node 40 | dfs2(x, cur); 41 | System.out.println(cur + " "); 42 | } 43 | } 44 | } 45 | 46 | static void dfs3(int cur, int par) { 47 | tin[cur] = ++tme; 48 | for (int x : gr[cur]) { 49 | if (x != par) { 50 | // x is child node 51 | dfs3(x, cur); 52 | } 53 | } 54 | tout[cur] = tme; 55 | } 56 | 57 | public static void main(String[] args){ 58 | 59 | Scanner scn = new Scanner(System.in); 60 | int n = scn.nextInt(); 61 | for (int i = 0; i < n-1; i++) { 62 | int x = scn.nextInt(), y = scn.nextInt(); 63 | gr[x].add(y); 64 | gr[y].add(x); 65 | } 66 | 67 | 68 | // tme = 1; 69 | // dfs1(1, 0); 70 | 71 | 72 | // dfs2(1, 0); 73 | 74 | tme = 0; 75 | dfs3(1, 0); 76 | 77 | for (int i = 1; i <= n; i++) { 78 | System.out.println(i + " " + tin[i] + " " + tout[i] ); 79 | } 80 | 81 | for (int i = 1; i <= n; i++) { 82 | flat[tin[i]] = i; 83 | } 84 | 85 | for (int i = 1; i <= n; i++) { 86 | System.out.print(flat[i] + " "); 87 | } 88 | 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /Graphs Java/src/FloodFill/MakeLargestIsland.java: -------------------------------------------------------------------------------- 1 | package FloodFill; 2 | 3 | import java.util.HashSet; 4 | import java.util.Scanner; 5 | 6 | public class MakeLargestIsland { 7 | 8 | static final int N = 100; 9 | 10 | static int[][] a= new int[N][N]; 11 | static int[][] vis = new int[N][N]; 12 | static int[] col_cnt = new int[N]; 13 | 14 | static int n, m; 15 | 16 | static int[] dx = {0, 0, 1, -1}; 17 | static int[] dy = {1, -1, 0, 0}; 18 | 19 | 20 | static void flood_fill(int x, int y, int col) { 21 | a[x][y] = col; 22 | col_cnt[col]++; 23 | vis[x][y] = 1; 24 | for (int i = 0; i < 4; i++) { 25 | int xx = x + dx[i]; 26 | int yy = y + dy[i]; 27 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && vis[xx][yy] == 0 && a[xx][yy] == 1) { 28 | flood_fill(xx, yy, col); 29 | } 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | 35 | Scanner scn = new Scanner(System.in); 36 | int n = scn.nextInt() ,m = scn.nextInt(); 37 | for (int i = 0; i < n; i++) { 38 | for (int j = 0; j < m; j++) { 39 | a[i][j] = scn.nextInt(); 40 | } 41 | } 42 | 43 | int total_count = 0; 44 | 45 | for (int i = 0; i < n; i++) { 46 | for (int j = 0; j < m; j++) { 47 | if (a[i][j] == 1 && vis[i][j] == 0) { 48 | total_count++; 49 | flood_fill(i, j, total_count); 50 | } 51 | } 52 | } 53 | 54 | int largest_island = 0; 55 | 56 | for (int i = 1; i <= total_count; i++) { 57 | largest_island = Math.max(largest_island, col_cnt[i]); 58 | } 59 | 60 | for (int i = 0; i < n; i++) { 61 | for (int j = 0; j < m; j++) { 62 | if (a[i][j] == 0) { 63 | // can be converted 64 | HashSet St = new HashSet<>(); 65 | for (int k = 0; k < 4; k++) { 66 | int ii = i + dx[k]; 67 | int jj = j + dy[k]; 68 | if (ii >= 0 && ii < n && jj >= 0 && jj < m) { 69 | St.add(a[ii][jj]); 70 | } 71 | } 72 | int ans = 1; 73 | for (int x : St) { 74 | ans += col_cnt[x]; 75 | } 76 | largest_island = Math.max(largest_island, ans); 77 | } 78 | } 79 | } 80 | 81 | System.out.print( largest_island ); 82 | 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Graphs Java/src/FloodFill/alphabetMatch.java: -------------------------------------------------------------------------------- 1 | package FloodFill; 2 | 3 | import java.util.Scanner; 4 | 5 | public class alphabetMatch { 6 | 7 | 8 | static final int N = 100; 9 | 10 | static int[][] a= new int[N][N]; 11 | static int[][] vis = new int[N][N]; 12 | 13 | static int n, m; 14 | 15 | static int[] dx = {0, 0, 1, -1}; 16 | static int[] dy = {1, -1, 0, 0}; 17 | 18 | static void flood_fill(int x, int y, int col) { 19 | vis[x][y] = 1; 20 | for (int i = 0; i < 4; i++) { 21 | int xx = x + dx[i]; 22 | int yy = y + dy[i]; 23 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && a[x][y] == a[xx][yy] && vis[xx][yy] == 0) { 24 | flood_fill(xx, yy, col); 25 | } 26 | } 27 | a[x][y] = col; 28 | } 29 | 30 | public static void main(String[] args) { 31 | 32 | Scanner scn = new Scanner(System.in); 33 | int n = scn.nextInt() ,m = scn.nextInt(); 34 | 35 | for (int i = 0; i < n; i++) { 36 | for (int j = 0; j < m; j++) { 37 | char ch = scn.next().charAt(0); 38 | a[i][j] = ch - 'A' + 1; 39 | } 40 | } 41 | 42 | int col = 0; 43 | 44 | for (int i = 0; i < n; i++) { 45 | for (int j = 0; j < m; j++) { 46 | if (vis[i][j] == 0) { 47 | col++; 48 | flood_fill(i, j, col); 49 | } 50 | } 51 | } 52 | 53 | for (int i = 0; i < n; i++) { 54 | for (int j = 0; j < m; j++) { 55 | System.out.print(a[i][j] + " "); 56 | } 57 | } 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Graphs Java/src/FloodFill/colorCount.java: -------------------------------------------------------------------------------- 1 | package FloodFill; 2 | 3 | import java.util.Scanner; 4 | 5 | public class colorCount { 6 | static final int N = 100; 7 | 8 | static int[][] a= new int[N][N]; 9 | static int[][] vis = new int[N][N]; 10 | static int[] col_cnt = new int[N]; 11 | 12 | static int n, m; 13 | 14 | static int[] dx = {0, 0, 1, -1}; 15 | static int[] dy = {1, -1, 0, 0}; 16 | 17 | 18 | 19 | static void flood_fill(int x, int y, int col) { 20 | a[x][y] = col; 21 | col_cnt[col]++; 22 | vis[x][y] = 1; 23 | for (int i = 0; i < 4; i++) { 24 | int xx = x + dx[i]; 25 | int yy = y + dy[i]; 26 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && vis[xx][yy] == 0 && a[xx][yy] == 1) { 27 | flood_fill(xx, yy, col); 28 | } 29 | } 30 | } 31 | 32 | public static void main(String[] args) 33 | { 34 | 35 | Scanner scn = new Scanner(System.in); 36 | int n = scn.nextInt() ,m = scn.nextInt(); 37 | for (int i = 0; i < n; i++) { 38 | for (int j = 0; j < m; j++) { 39 | a[i][j] = scn.nextInt(); 40 | } 41 | } 42 | 43 | int total_count = 0; 44 | 45 | for (int i = 0; i < n; i++) { 46 | for (int j = 0; j < m; j++) { 47 | if (a[i][j] == 1 && vis[i][j] == 0) { 48 | total_count++; 49 | flood_fill(i, j, total_count); 50 | } 51 | } 52 | } 53 | 54 | for (int i = 0; i < n; i++) { 55 | for (int j = 0; j < m; j++) { 56 | System.out.println( a[i][j] + " "); 57 | } System.out.println(); 58 | } 59 | 60 | for (int i = 1; i <= total_count; i++) { 61 | System.out.print( i + " " + col_cnt[i] + '\n'); 62 | } 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Graphs Java/src/FloodFill/graphInput.java: -------------------------------------------------------------------------------- 1 | package FloodFill; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class graphInput { 7 | 8 | final static int N = (int) (1e5 + 1); 9 | 10 | static ArrayList[] gr = new ArrayList[N]; 11 | 12 | static { 13 | for(int i = 0; i < gr.length; i++){ 14 | gr[i] = new ArrayList<>(); 15 | } 16 | } 17 | 18 | public static void main(String[] args){ 19 | 20 | Scanner scn = new Scanner(System.in); 21 | int n = scn.nextInt(); 22 | int m = scn.nextInt(); 23 | 24 | for(int i = 0; i < m; i++){ 25 | int x = scn.nextInt(); 26 | int y = scn.nextInt(); 27 | 28 | gr[x].add(y); 29 | gr[y].add(x); 30 | 31 | } 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Graphs Java/src/FloodFill/largestIsland.java: -------------------------------------------------------------------------------- 1 | package FloodFill; 2 | 3 | import java.util.HashSet; 4 | import java.util.Scanner; 5 | import java.util.Set; 6 | 7 | public class largestIsland { 8 | 9 | 10 | static final int N = 100; 11 | 12 | static int[][] a= new int[N][N]; 13 | static int[][] vis = new int[N][N]; 14 | static int[] col_cnt = new int[N]; 15 | 16 | static int n, m; 17 | 18 | static int[] dx = {0, 0, 1, -1}; 19 | static int[] dy = {1, -1, 0, 0}; 20 | 21 | static void flood_fill(int x, int y, int col) { 22 | a[x][y] = col; 23 | col_cnt[col]++; 24 | vis[x][y] = 1; 25 | for (int i = 0; i < 4; i++) { 26 | int xx = x + dx[i]; 27 | int yy = y + dy[i]; 28 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && vis[xx][yy] == 0 && a[xx][yy] == 1) { 29 | flood_fill(xx, yy, col); 30 | } 31 | } 32 | } 33 | 34 | public static void main(String[] args) { 35 | 36 | Scanner scn = new Scanner(System.in); 37 | int n = scn.nextInt() ,m = scn.nextInt(); 38 | for (int i = 0; i < n; i++) { 39 | for (int j = 0; j < m; j++) { 40 | a[i][j] = scn.nextInt(); 41 | } 42 | } 43 | 44 | int total_count = 0; 45 | 46 | for (int i = 0; i < n; i++) { 47 | for (int j = 0; j < m; j++) { 48 | if (a[i][j] == 1 && vis[i][j] == 0) { 49 | total_count++; 50 | flood_fill(i, j, total_count); 51 | } 52 | } 53 | } 54 | 55 | int largest_island = 0; 56 | 57 | for (int i = 1; i <= total_count; i++) { 58 | largest_island = Math.max(largest_island, col_cnt[i]); 59 | } 60 | 61 | for (int i = 0; i < n; i++) { 62 | for (int j = 0; j < m; j++) { 63 | if (a[i][j] == 0) { 64 | // can be converted 65 | Set St = new HashSet<>(); 66 | for (int k = 0; k < 4; k++) { 67 | int ii = i + dx[k]; 68 | int jj = j + dy[k]; 69 | if (ii >= 0 && ii < n && jj >= 0 && jj < m) { 70 | St.add(a[ii][jj]); 71 | } 72 | } 73 | int ans = 1; 74 | for (int x : St) { 75 | ans += col_cnt[x]; 76 | } 77 | largest_island = Math.max(largest_island, ans); 78 | } 79 | } 80 | } 81 | 82 | System.out.println(largest_island); 83 | 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Graphs Java/src/FloodFill/totalConnectedComponent.java: -------------------------------------------------------------------------------- 1 | package FloodFill; 2 | 3 | import java.util.Scanner; 4 | 5 | public class totalConnectedComponent { 6 | 7 | 8 | static final int N = 100; 9 | 10 | static int[][] a= new int[N][N]; 11 | static int[][] vis = new int[N][N]; 12 | 13 | static int n, m; 14 | 15 | static int[] dx = {0, 0, 1, -1}; 16 | static int[] dy = {1, -1, 0, 0}; 17 | 18 | 19 | static void flood_fill(int x, int y) { 20 | a[x][y] = 0; 21 | for (int i = 0; i < 4; i++) { 22 | int xx = x + dx[i]; 23 | int yy = y + dy[i]; 24 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && a[xx][yy] == 1) { 25 | flood_fill(xx, yy); 26 | } 27 | } 28 | } 29 | 30 | public static void main(String[] args) 31 | { 32 | 33 | Scanner scn = new Scanner(System.in); 34 | int n = scn.nextInt() ,m = scn.nextInt(); 35 | for (int i = 0; i < n; i++) { 36 | for (int j = 0; j < m; j++) { 37 | a[i][j] = scn.nextInt(); 38 | } 39 | } 40 | 41 | int total_count = 0; 42 | 43 | 44 | for (int i = 0; i < n; i++) { 45 | for (int j = 0; j < m; j++) { 46 | if (a[i][j] == 1) { 47 | total_count++; 48 | flood_fill(i, j); 49 | } 50 | } 51 | } 52 | 53 | System.out.println(total_count); 54 | 55 | } 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /Graphs Java/src/GraphRepresentation/adj_list_01.java: -------------------------------------------------------------------------------- 1 | package GraphRepresentation; 2 | import java.util.ArrayList; 3 | 4 | 5 | public class adj_list_01{ 6 | 7 | static class Graph{ 8 | int V; 9 | ArrayList[] list; 10 | 11 | public Graph(int v){ 12 | V = v; 13 | list = new ArrayList[v]; 14 | for(int i = 0; i < v; i++){ 15 | list[i] = new ArrayList<>(); 16 | } 17 | } 18 | 19 | void addEdge(int i, int j, boolean unDirected){ 20 | list[i].add(j); 21 | if(unDirected) 22 | list[j].add(i); 23 | } 24 | 25 | void printAdjList(){ 26 | // Iterate over all the rows!! 27 | for(int i = 0; i < V; i++){ 28 | System.out.print(i + " --> "); 29 | // Iterating over one row! 30 | for(int node: list[i]){ 31 | System.out.print(node + ", "); 32 | } 33 | 34 | System.out.println(); 35 | } 36 | } 37 | } 38 | 39 | public static void main(String[] args){ 40 | Graph g = new Graph(6); 41 | 42 | g.addEdge(0,1, true); 43 | g.addEdge(0,4, true); 44 | g.addEdge(2,1, true); 45 | g.addEdge(3,4, true); 46 | g.addEdge(4,5, true); 47 | g.addEdge(2,3, true); 48 | g.addEdge(3,5, true); 49 | g.printAdjList(); 50 | 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /Graphs Java/src/GraphRepresentation/adj_list_02.java: -------------------------------------------------------------------------------- 1 | package GraphRepresentation; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class adj_list_02 { 8 | 9 | static class Node{ 10 | String name; 11 | ArrayList nbrs; 12 | 13 | Node(String name){ 14 | this.name = name; 15 | nbrs = new ArrayList<>(); 16 | } 17 | } 18 | 19 | static class Graph{ 20 | 21 | HashMap mp; 22 | 23 | public Graph(ArrayList cities){ 24 | mp = new HashMap<>(); 25 | for(String city: cities){ 26 | mp.put(city, new Node(city)); 27 | } 28 | } 29 | 30 | public void addEdge(String x, String y, boolean unDirected){ 31 | mp.get(x).nbrs.add(y); 32 | if(unDirected){ 33 | mp.get(y).nbrs.add(x); 34 | } 35 | } 36 | 37 | public void printAdjList(){ 38 | for(Map.Entry cityPair: mp.entrySet()){ 39 | System.out.print(cityPair.getKey() + " --> "); 40 | for(String nbrs: cityPair.getValue().nbrs){ 41 | System.out.print(nbrs + ", "); 42 | } 43 | System.out.println(); 44 | } 45 | } 46 | 47 | 48 | } 49 | 50 | public static void main(String[] args){ 51 | 52 | ArrayList cities = new ArrayList<>(); 53 | cities.add("Delhi"); 54 | cities.add("London"); 55 | cities.add("Paris"); 56 | cities.add( "New York"); 57 | 58 | Graph g = new Graph(cities); 59 | g.addEdge("Delhi", "London" , true); 60 | g.addEdge("New York","London", true); 61 | g.addEdge("Delhi","Paris" , true); 62 | g.addEdge("Paris","New York" , true); 63 | 64 | g.printAdjList(); 65 | 66 | } 67 | } 68 | 69 | -------------------------------------------------------------------------------- /Graphs Java/src/GraphRepresentation/adj_list_02_node.java: -------------------------------------------------------------------------------- 1 | package GraphRepresentation; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class adj_list_02_node { 8 | 9 | static class Node{ 10 | String name; 11 | ArrayList nbrs; 12 | 13 | Node(String name){ 14 | this.name = name; 15 | nbrs = new ArrayList<>(); 16 | } 17 | } 18 | 19 | static class Graph{ 20 | 21 | HashMap mp; 22 | 23 | public Graph(ArrayList cities){ 24 | mp = new HashMap<>(); 25 | for(String city: cities){ 26 | mp.put(city, new Node(city)); 27 | } 28 | } 29 | 30 | public void addEdge(String x, String y, boolean unDirected){ 31 | mp.get(x).nbrs.add(y); 32 | if(unDirected){ 33 | mp.get(y).nbrs.add(x); 34 | } 35 | } 36 | 37 | public void printAdjList(){ 38 | for(Map.Entry cityPair: mp.entrySet()){ 39 | System.out.print(cityPair.getKey() + " --> "); 40 | for(String nbrs: cityPair.getValue().nbrs){ 41 | System.out.print(nbrs + ", "); 42 | } 43 | System.out.println(); 44 | } 45 | } 46 | 47 | 48 | } 49 | 50 | public static void main(String[] args){ 51 | 52 | ArrayList cities = new ArrayList<>(); 53 | cities.add("Delhi"); 54 | cities.add("London"); 55 | cities.add("Paris"); 56 | cities.add( "New York"); 57 | 58 | Graph g = new Graph(cities); 59 | g.addEdge("Delhi", "London" , true); 60 | g.addEdge("New York","London", true); 61 | g.addEdge("Delhi","Paris" , true); 62 | g.addEdge("Paris","New York" , true); 63 | 64 | g.printAdjList(); 65 | 66 | } 67 | } 68 | 69 | -------------------------------------------------------------------------------- /Graphs Java/src/LCA/_2Pointer.java: -------------------------------------------------------------------------------- 1 | package LCA; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | public class _2Pointer { 6 | 7 | static final int N = (int) (1e5 + 1); 8 | 9 | static ArrayList[] gr = new ArrayList[N]; 10 | 11 | static { 12 | for(int i = 0; i < N; i++){ 13 | gr[i] = new ArrayList<>(); 14 | } 15 | } 16 | 17 | 18 | static int[] dep = new int[N]; 19 | static int[] Par = new int[N]; 20 | 21 | static void dfs(int cur, int par) { 22 | Par[cur] = par; 23 | dep[cur] = dep[par] + 1; 24 | for (int x : gr[cur]) { 25 | if (x != par) { 26 | dfs(x, cur); 27 | } 28 | } 29 | } 30 | 31 | static int LCA(int u, int v) { 32 | if (u == v) return u; 33 | 34 | if (dep[u] < dep[v]){ 35 | int temp = u; 36 | u = v; 37 | v = temp; 38 | } 39 | // depth of u is more than depth of v 40 | 41 | int diff = dep[u] - dep[v]; 42 | 43 | // depth of both nodes same 44 | while (diff-- != 0) { 45 | u = Par[u]; 46 | } 47 | 48 | // until they are equal nodes keep climbing 49 | while (u != v) { 50 | u = Par[u]; 51 | v = Par[v]; 52 | } 53 | 54 | return u; 55 | } 56 | 57 | public static void main(String[] args){ 58 | 59 | Scanner scn = new Scanner(System.in); 60 | int n = scn.nextInt(); 61 | for (int i = 0; i < n-1; i++) { 62 | int x = scn.nextInt(), y = scn.nextInt(); 63 | gr[x].add(y); 64 | gr[y].add(x); 65 | } 66 | 67 | dfs(1, 0); 68 | 69 | 70 | System.out.println(LCA(9,12)); 71 | System.out.println(LCA(10,8)); 72 | System.out.println(LCA(9,11)); 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Graphs Java/src/LCA/sparseTable.java: -------------------------------------------------------------------------------- 1 | package LCA; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class sparseTable { 7 | 8 | static final int N = (int) 1e5, M = 20; 9 | 10 | static ArrayList[] gr = new ArrayList[N]; 11 | 12 | static { 13 | for(int i = 0; i < N; i++){ 14 | gr[i] = new ArrayList<>(); 15 | } 16 | } 17 | 18 | static int[] dep = new int[N]; 19 | static int[][] Par = new int[N][M]; 20 | 21 | 22 | // O(N*M) 23 | static void dfs(int cur, int par) { 24 | dep[cur] = dep[par] + 1; 25 | 26 | Par[cur][0] = par; 27 | for (int j = 1; j < M; j++) { 28 | Par[cur][j] = Par[Par[cur][j - 1]][j - 1]; 29 | } 30 | 31 | for (int x : gr[cur]) { 32 | if (x != par) { 33 | dfs(x, cur); 34 | } 35 | } 36 | } 37 | 38 | // O(M) = logN 39 | static int LCA(int u, int v) { 40 | if (u == v) return u; 41 | if (dep[u] < dep[v]) { 42 | int temp = u; 43 | u = v; 44 | v = temp; 45 | } 46 | int diff = dep[u] - dep[v]; 47 | for (int j = M - 1; j >= 0; j--) { 48 | if (((diff >> j) & 1) != 0) { 49 | // jth bit of diff is set 50 | u = Par[u][j]; 51 | } 52 | } 53 | // u and v are on the same level 54 | for (int j = M - 1; j >= 0; j--) { 55 | if (Par[u][j] != Par[v][j]) { 56 | u = Par[u][j]; 57 | v = Par[v][j]; 58 | } 59 | } 60 | 61 | // Par[v][0] 62 | return Par[u][0]; 63 | } 64 | 65 | // O(1) 66 | static int LengthFromUtoV(int u, int v) { 67 | int lca = LCA(u, v); 68 | return dep[u] + dep[v] - 2 * dep[lca]; 69 | } 70 | 71 | public static void main(String[] args){ 72 | Scanner scn = new Scanner(System.in); 73 | int n = scn.nextInt(); 74 | for (int i = 0; i < n-1; i++) { 75 | int x = scn.nextInt(), y = scn.nextInt(); 76 | gr[x].add(y); 77 | gr[y].add(x); 78 | } 79 | 80 | 81 | dfs(1, 0); 82 | 83 | 84 | System.out.print( LCA(4, 5) + "\n"); 85 | System.out.print( LCA(4, 6) + "\n"); 86 | System.out.print( LCA(4, 3) + "\n"); 87 | System.out.print( LCA(2, 3) + "\n"); 88 | System.out.print( LengthFromUtoV(2, 3) + "\n"); 89 | 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Graphs Java/src/MinimumSpanningTree/Kruskal.java: -------------------------------------------------------------------------------- 1 | package MinimumSpanningTree; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | 8 | public class Kruskal { 9 | 10 | static class DSU{ 11 | int[] parent, rank; 12 | 13 | public DSU(int n){ 14 | parent = new int[n]; 15 | rank = new int[n]; 16 | 17 | //parent -1, rank = 1 18 | for(int i=0;i> edgeList; 55 | int V; 56 | 57 | public Graph(int V) { 58 | this.V = V; 59 | edgeList = new ArrayList<>(); 60 | } 61 | 62 | void addEdge(int x,int y,int w){ 63 | ArrayList list = new ArrayList<>(); 64 | list.add(w); 65 | list.add(x); 66 | list.add(y); 67 | edgeList.add(list); 68 | } 69 | 70 | int kruskal_mst(){ 71 | //Main Logic = Easy!!! 72 | //1. Sort all the edges based upon weight 73 | edgeList.sort(new Comparator>() { 74 | @Override 75 | public int compare(ArrayList o1, ArrayList o2) { 76 | return o1.get(0) - o2.get(0); 77 | } 78 | }); 79 | 80 | //Init a DSU 81 | DSU s = new DSU(V); 82 | 83 | int ans = 0; 84 | for(List edge : edgeList){ 85 | 86 | int w = edge.get(0); 87 | int x = edge.get(1); 88 | int y = edge.get(2); 89 | 90 | //take that edge in MST if it doesnt form a cycle 91 | if(s.find(x)!=s.find(y)){ 92 | s.unite(x,y); 93 | ans += w; 94 | } 95 | 96 | } 97 | return ans; 98 | } 99 | 100 | 101 | } 102 | 103 | public static void main(String[] args){ 104 | Scanner scn = new Scanner(System.in); 105 | int n = scn.nextInt(),m = scn.nextInt(); 106 | 107 | 108 | Graph g = new Graph(n); 109 | for(int i=0;i[] l; 19 | int V; 20 | 21 | 22 | public Graph(int n){ 23 | V = n; 24 | l = new ArrayList[n]; 25 | for(int i = 0; i < n; i++){ 26 | l[i] = new ArrayList<>(); 27 | } 28 | } 29 | 30 | void addEdge(int x,int y,int w){ 31 | l[x].add(new Pair(y,w)); 32 | l[y].add(new Pair(x,w)); 33 | } 34 | 35 | int prim_mst(){ 36 | 37 | Queue Q = new PriorityQueue<>(new Comparator() { 38 | @Override 39 | public int compare(Pair o1, Pair o2) { 40 | return o1.first - o2.first; 41 | } 42 | 43 | }); 44 | 45 | // 46 | 47 | //another array 48 | //visited array that denotes whether a node has been included in MST or Not 49 | boolean[] vis = new boolean[V]; 50 | int ans = 0; 51 | 52 | //begin 53 | Q.add(new Pair(0,0)); // weight, node 54 | 55 | while(!Q.isEmpty()){ 56 | //pick out the edge with min weight 57 | Pair best = Q.poll(); 58 | 59 | int to = best.second; 60 | int weight = best.first; 61 | 62 | if(vis[to]){ 63 | //discard the edge, and continue 64 | continue; 65 | } 66 | 67 | //otherwise take the current edge 68 | ans += weight; 69 | vis[to] = true; 70 | 71 | //add the new edges in the queue 72 | for(Pair x:l[to]){ 73 | if(!vis[x.first]){ 74 | Q.add(new Pair(x.second,x.first)); 75 | } 76 | } 77 | } 78 | return ans; 79 | } 80 | 81 | }; 82 | 83 | public static void main(String[] args){ 84 | 85 | Scanner scn = new Scanner(System.in); 86 | int n = scn.nextInt(),m = scn.nextInt(); 87 | 88 | Graph g = new Graph(n); 89 | for(int i=0;i[] gr = new ArrayList[N]; 13 | 14 | static { 15 | for(int i = 0; i < N; i++){ 16 | gr[i] = new ArrayList<>(); 17 | } 18 | } 19 | 20 | static int[] sub = new int[N]; 21 | static int[] dp = new int[N]; 22 | 23 | // sum of subtree sizes of all the nodes 24 | static void dfs(int cur, int par) { 25 | sub[cur] = 1; 26 | dp[cur] = 0; 27 | 28 | for (int x : gr[cur]) { 29 | if (x != par) { 30 | dfs(x, cur); 31 | dp[cur] += dp[x]; 32 | sub[cur] += sub[x]; 33 | } 34 | } 35 | 36 | dp[cur] += sub[cur]; 37 | } 38 | 39 | static int ans = 0; 40 | 41 | static void dfs1(int cur, int par) { 42 | // dp values are according to as cur is the root of the tree 43 | System.out.println(cur + " " + dp[cur]); 44 | ans = Math.max(ans, dp[cur]); 45 | 46 | for (int x : gr[cur]) { 47 | if (x != par) { 48 | // remove x from subtree of cur 49 | dp[cur] -= dp[x]; 50 | dp[cur] -= sub[x]; 51 | sub[cur] -= sub[x]; 52 | // now add cur as the subtree of x 53 | sub[x] += sub[cur]; 54 | dp[x] += dp[cur]; 55 | dp[x] += sub[cur]; 56 | 57 | dfs1(x, cur); 58 | 59 | // come back from x 60 | // rollback the changes as original tree 61 | dp[x] -= sub[cur]; 62 | dp[x] -= dp[cur]; 63 | sub[x] -= sub[cur]; 64 | sub[cur] += sub[x]; 65 | dp[cur] += sub[x]; 66 | dp[cur] += dp[x]; 67 | 68 | } 69 | } 70 | 71 | } 72 | public static void main(String[] args) { 73 | Scanner scn = new Scanner(System.in); 74 | int n = scn.nextInt(); 75 | for (int i = 0; i < n - 1; i++) { 76 | int x = scn.nextInt(), y = scn.nextInt(); 77 | gr[x].add(y); 78 | gr[y].add(x); 79 | } 80 | 81 | 82 | dfs(1, 0); 83 | 84 | // for (int i = 1; i <= n; i++) { 85 | // cout << dp[i] << " " << sub[i] << '\n'; 86 | // } 87 | 88 | dfs1(1, 0); 89 | 90 | System.out.println(ans); 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /Graphs Java/src/ReRooting/bruteForce.java: -------------------------------------------------------------------------------- 1 | package ReRooting; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class bruteForce { 7 | 8 | 9 | public static int N = (int) 1e5; 10 | 11 | static ArrayList[] gr = new ArrayList[N]; 12 | 13 | static { 14 | for(int i = 0; i < N; i++){ 15 | gr[i] = new ArrayList<>(); 16 | } 17 | } 18 | 19 | static int[] sub = new int[N]; 20 | 21 | // sum of subtree sizes of all the nodes 22 | static int dfs(int cur, int par) { 23 | sub[cur] = 1; 24 | 25 | int sum = 0; 26 | 27 | for (int x : gr[cur]) { 28 | if (x != par) { 29 | 30 | sum += dfs(x, cur); 31 | sub[cur] += sub[x]; 32 | 33 | } 34 | } 35 | 36 | sum += sub[cur]; 37 | 38 | return sum; 39 | } 40 | 41 | public static void main(String[] args) { 42 | Scanner scn = new Scanner(System.in); 43 | int n = scn.nextInt(); 44 | for (int i = 0; i < n - 1; i++) { 45 | int x = scn.nextInt(), y = scn.nextInt(); 46 | gr[x].add(y); 47 | gr[y].add(x); 48 | } 49 | 50 | 51 | int ans = 0; 52 | for (int i = 1; i <= n; i++) { 53 | ans = Math.max(ans, dfs(i, 0)); 54 | } 55 | 56 | // cout << dfs(3, 0) << '\n'; 57 | // O(n*n) 58 | 59 | System.out.println(ans); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Graphs Java/src/ShortestPath/Djikstra.java: -------------------------------------------------------------------------------- 1 | package ShortestPath; 2 | 3 | 4 | import java.util.*; 5 | 6 | public class Djikstra { 7 | 8 | static class Pair implements Comparable{ 9 | int first, second; 10 | 11 | Pair(int a,int b){ 12 | first = a; 13 | second = b; 14 | } 15 | 16 | @Override 17 | public int compareTo(Pair o) { 18 | if(this.first != o.first) 19 | return this.first - o.first; 20 | return this.second - o.second; 21 | } 22 | } 23 | 24 | 25 | static class Graph{ 26 | 27 | int V; 28 | List[] l; 29 | 30 | 31 | public Graph(int v){ 32 | V = v; 33 | l = new ArrayList[V]; 34 | for(int i = 0 ;i < V; i++){ 35 | l[i] = new ArrayList<>(); 36 | } 37 | } 38 | 39 | void addEdge(int u,int v,int wt, boolean undir){ 40 | 41 | l[u].add(new Pair(wt,v)); 42 | if(undir){ 43 | l[v].add(new Pair(wt,u)); 44 | } 45 | } 46 | 47 | int dijkstra(int src,int dest){ 48 | 49 | //Data Structures 50 | int[] dist = new int[V]; 51 | Arrays.fill(dist, Integer.MAX_VALUE); 52 | 53 | SortedSet s = new TreeSet<>(); 54 | 55 | //1. Init 56 | dist[src] = 0; 57 | s.add(new Pair(0,src)); 58 | 59 | while(!s.isEmpty()){ 60 | 61 | Pair it = s.first(); 62 | int node = it.second; 63 | int distTillNow = it.first; 64 | s.remove(it); //Pop 65 | 66 | //Iterate over the nbrs of node 67 | for(Pair nbrPair : l[node]){ 68 | //...... 69 | 70 | int nbr = nbrPair.second; 71 | int currentEdge = nbrPair.first; 72 | 73 | if(distTillNow + currentEdge < dist[nbr]){ 74 | //remove if nbr already exist in the set 75 | 76 | s.remove(new Pair(dist[nbr], nbr)); 77 | 78 | 79 | //insert the updated value with the new dist 80 | dist[nbr] = distTillNow + currentEdge; 81 | s.add(new Pair(dist[nbr],nbr)); 82 | 83 | } 84 | 85 | } 86 | 87 | } 88 | //Single Source Shortest Dist to all other nodes 89 | for(int i=0;i dist[i][k] + dist[k][j]){ 22 | dist[i][j] = dist[i][k] + dist[k][j]; 23 | } 24 | } 25 | 26 | } 27 | } 28 | return dist; 29 | } 30 | 31 | 32 | public static void main(String[] args){ 33 | 34 | 35 | 36 | int[][] graph = { 37 | {0,INF,-2,INF}, 38 | {4,0,3,INF}, 39 | {INF,INF,0,2}, 40 | {INF,-1,INF,0} 41 | }; 42 | 43 | 44 | int[][] result = floyd_warshall(graph); 45 | for(int i=0;i { 10 | int x; 11 | int y; 12 | int dist; 13 | 14 | Node(int x, int y, int dist) { 15 | this.x = x; 16 | this.y = y; 17 | this.dist = dist; 18 | } 19 | 20 | @Override 21 | public int compareTo(Node o) { 22 | if(o.dist != this.dist) 23 | return this.dist - o.dist; 24 | if(o.x != this.x){ 25 | return this.x - o.x; 26 | } 27 | 28 | return o.y - this.y; 29 | } 30 | } 31 | 32 | 33 | 34 | static int shortest_path(int[][] grid){ 35 | //return the shortest path len 36 | 37 | int m = grid.length; 38 | int n = grid[0].length; 39 | 40 | int i = 0; 41 | int j = 0; 42 | 43 | //2D vector to denote of each cell 44 | int[][] dist = new int[m+1][n+1] ; 45 | for(int[] v: dist){ 46 | Arrays.fill(v, Integer.MAX_VALUE); 47 | } 48 | 49 | dist[i][j] = grid[0][0]; 50 | SortedSet s = new TreeSet<>(); 51 | 52 | s.add(new Node(0,0,dist[0][0])); 53 | 54 | int dx[] = {0,0,1,-1}; 55 | int dy[] = {1,-1,0,0}; 56 | 57 | 58 | while(!s.isEmpty()){ 59 | 60 | Node it = s.first(); 61 | int cx = it.x; 62 | int cy = it.y; 63 | int cd = it.dist; 64 | s.remove(it); 65 | 66 | //update nbrs 67 | for(int k=0;k<4;k++){ 68 | int nx = cx + dx[k]; 69 | int ny = cy + dy[k]; 70 | 71 | if(nx>=0 && nx=0 && ny[] gr = new ArrayList[N], grr = new ArrayList[N], components = new ArrayList[N]; 14 | 15 | static { 16 | for(int i = 0; i < N; i++){ 17 | gr[i] = new ArrayList<>(); 18 | grr[i] = new ArrayList<>(); 19 | components[i] = new ArrayList<>(); 20 | } 21 | } 22 | static boolean[] vis = new boolean[N]; 23 | static int[] col = new int[N]; 24 | static ArrayList order = new ArrayList<>(); 25 | 26 | 27 | // topological sorting 28 | static void dfs1(int cur) { 29 | vis[cur] = true; 30 | for (int x : gr[cur]) { 31 | if (!vis[x]) dfs1(x); 32 | } 33 | order.add(cur); 34 | } 35 | 36 | static void dfs2(int cur, int comp) { 37 | vis[cur] = true; 38 | col[cur] = comp; 39 | components[comp].add(cur); 40 | for (int x : grr[cur]) { 41 | if (!vis[x]) 42 | dfs2(x, comp); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | 48 | Scanner scn = new Scanner(System.in); 49 | int n = scn.nextInt(), m = scn.nextInt(); 50 | 51 | for (int i = 0; i < m; i++) { 52 | int x = scn.nextInt(), y = scn.nextInt(); 53 | gr[x].add(y); 54 | grr[y].add(x); 55 | 56 | } 57 | 58 | for (int i = 1; i <= n; i++) { 59 | if (!vis[i]) 60 | dfs1(i); 61 | } 62 | 63 | Collections.reverse(order); 64 | Arrays.fill(vis, false); 65 | 66 | 67 | int comp = 1; 68 | for (int x : order) { 69 | if (!vis[x]) 70 | dfs2(x, comp++); 71 | } 72 | 73 | for (int i = 1; i <= n; i++) { 74 | System.out.println(i + " " + col[i]); 75 | 76 | } 77 | 78 | System.out.println( "Total strongly components are -> " + (comp - 1) ); 79 | // complexity O(n+m) 80 | 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /Graphs Java/src/StronglyConnectedComponent/TopologicalOrder.java: -------------------------------------------------------------------------------- 1 | package StronglyConnectedComponent; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Scanner; 6 | 7 | public class TopologicalOrder { 8 | 9 | static final int N = (int)(1e5 + 1); 10 | 11 | static ArrayList[] gr = new ArrayList[N]; 12 | static ArrayList order; 13 | static { 14 | for(int i = 0 ; i < N ; i++){ 15 | gr[i] = new ArrayList<>(); 16 | } 17 | } 18 | 19 | static boolean[] vis = new boolean[N]; 20 | 21 | static void dfs(int cur, int par) { 22 | vis[cur] = true; 23 | for (int x : gr[cur]) { 24 | if (!vis[x]) { 25 | dfs(x, cur); 26 | } 27 | } 28 | // I am here because I came back from the subtree 29 | order.add(cur); 30 | return; 31 | } 32 | 33 | 34 | public static void main(String[] args) { 35 | 36 | Scanner scn = new Scanner(System.in); 37 | int n = scn.nextInt(), m = scn.nextInt(); 38 | 39 | for (int i = 0; i < m; i++) { 40 | int x = scn.nextInt(), y = scn.nextInt(); 41 | gr[x].add(y); 42 | 43 | } 44 | 45 | 46 | for (int i = 1; i <= n; i++) { 47 | if (!vis[i]) dfs(i, 0); 48 | } 49 | 50 | Collections.reverse(order); 51 | 52 | for (int x : order) 53 | System.out.println(x); 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Graphs Java/src/TravellingSalesMan/travellingSalesMan.java: -------------------------------------------------------------------------------- 1 | package TravellingSalesMan; 2 | 3 | import java.util.Arrays; 4 | 5 | public class travellingSalesMan { 6 | 7 | 8 | 9 | static int tsp(int[][] dist, int setOfCities, int city,int n,int[][] dp){ 10 | 11 | //base case 12 | if(setOfCities == (1<[] gr = new ArrayList[N]; 11 | 12 | static { 13 | for(int i = 0; i < N; i++){ 14 | gr[i] = new ArrayList<>(); 15 | } 16 | } 17 | static int[] Par = new int[N]; 18 | 19 | static void dfs(int cur, int par) { 20 | Par[cur] = par; 21 | for (int x : gr[cur]) { 22 | if (x != par) { 23 | // x is child node 24 | dfs(x, cur); 25 | } 26 | } 27 | } 28 | 29 | public static void main(String[] args) 30 | { 31 | 32 | Scanner scn = new Scanner(System.in); 33 | int n = scn.nextInt(); 34 | for (int i = 0; i < n-1; i++) { 35 | int x = scn.nextInt(), y = scn.nextInt(); 36 | gr[x].add(y); 37 | gr[y].add(x); 38 | 39 | } 40 | 41 | dfs(1, 0); 42 | 43 | int x = 6; 44 | // print all ancestors of 5 45 | 46 | while (x > 0) { 47 | System.out.println(x); 48 | x = Par[x]; 49 | } 50 | 51 | 52 | 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Graphs Java/src/multiSourceBfs/BFSMinimumOperations.java: -------------------------------------------------------------------------------- 1 | package multiSourceBfs; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | import java.util.Scanner; 6 | 7 | public class BFSMinimumOperations { 8 | 9 | static class Pair{ 10 | int first, second; 11 | Pair(int a, int b){ 12 | first = a; 13 | second = b; 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | 19 | Scanner scn = new Scanner(System.in); 20 | int n = scn.nextInt(), m = scn.nextInt(); 21 | 22 | int[][] a = new int[n][m]; 23 | int[][] dist = new int[n][m]; 24 | Queue Q = new LinkedList<>(); 25 | 26 | int[] dx = {1, -1, 0, 0}; 27 | int[] dy = {0, 0, 1, -1}; 28 | 29 | for (int i = 0; i < n; i++) { 30 | for (int j = 0; j < m; j++) { 31 | a[i][j] = scn.nextInt(); 32 | dist[i][j] = Integer.MAX_VALUE; 33 | if (a[i][j] != 0) { 34 | Q.add(new Pair(i, j)); 35 | dist[i][j] = 0; 36 | } 37 | } 38 | } 39 | 40 | while (!Q.isEmpty()) { 41 | int x = Q.peek().first;; 42 | int y = Q.peek().second; 43 | Q.remove(); 44 | 45 | for (int i = 0; i < 4; i++) { 46 | int xx = x + dx[i]; 47 | int yy = y + dy[i]; 48 | 49 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && dist[xx][yy] == Integer.MAX_VALUE) { 50 | Q.add(new Pair(xx, yy)); 51 | dist[xx][yy] = dist[x][y] + 1; 52 | } 53 | 54 | } 55 | 56 | for (int i = 0; i < n; i++) { 57 | for (int j = 0; j < m; j++) { 58 | if (dist[i][j] == Integer.MAX_VALUE) System.out.print("# "); 59 | else System.out.print(dist[i][j] + " "); 60 | } 61 | System.out.println(); 62 | } 63 | System.out.println(); 64 | 65 | 66 | } 67 | 68 | for (int i = 0; i < n; i++) { 69 | for (int j = 0; j < m; j++) { 70 | System.out.print(dist[i][j] + " "); 71 | } 72 | System.out.println(); 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /Graphs Java/src/multiSourceBfs/MinimumDistance.java: -------------------------------------------------------------------------------- 1 | package multiSourceBfs; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | import java.util.Scanner; 6 | 7 | public class MinimumDistance { 8 | 9 | static class Pair{ 10 | int first, second; 11 | Pair(int a, int b){ 12 | first = a; 13 | second = b; 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | Scanner scn = new Scanner(System.in); 19 | int n = scn.nextInt(), m = scn.nextInt(); 20 | 21 | int[][] a = new int[n][m]; 22 | int[][] dist = new int[n][m]; 23 | Queue Q = new LinkedList<>(); 24 | 25 | int[] dx = {1, -1, 0, 0}; 26 | int[] dy = {0, 0, 1, -1}; 27 | 28 | for (int i = 0; i < n; i++) { 29 | for (int j = 0; j < m; j++) { 30 | a[i][j] = scn.nextInt(); 31 | dist[i][j] = Integer.MAX_VALUE; 32 | if (a[i][j] != 0) { 33 | Q.add(new Pair(i, j)); 34 | dist[i][j] = 0; 35 | } 36 | } 37 | } 38 | 39 | while (!Q.isEmpty()) { 40 | int x = Q.peek().first; 41 | ; 42 | int y = Q.peek().second; 43 | Q.remove(); 44 | 45 | for (int i = 0; i < 4; i++) { 46 | int xx = x + dx[i]; 47 | int yy = y + dy[i]; 48 | 49 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && dist[xx][yy] == Integer.MAX_VALUE) { 50 | Q.add(new Pair(xx, yy)); 51 | dist[xx][yy] = dist[x][y] + 1; 52 | } 53 | 54 | } 55 | 56 | for (int i = 0; i < n; i++) { 57 | for (int j = 0; j < m; j++) { 58 | if (dist[i][j] == Integer.MAX_VALUE) System.out.print("# n"); 59 | else System.out.print(dist[i][j] + " "); 60 | } 61 | System.out.println(); 62 | } 63 | System.out.println(); 64 | 65 | 66 | } 67 | 68 | for (int i = 0; i < n; i++) { 69 | for (int j = 0; j < m; j++) { 70 | System.out.print(dist[i][j] + " "); 71 | } 72 | System.out.println(); 73 | } 74 | } 75 | 76 | 77 | 78 | 79 | 80 | 81 | } 82 | -------------------------------------------------------------------------------- /Graphs Java/src/multiSourceBfs/ShortestPathFirstToLastRow.java: -------------------------------------------------------------------------------- 1 | package multiSourceBfs; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | import java.util.Scanner; 6 | 7 | public class ShortestPathFirstToLastRow { 8 | 9 | static class Pair{ 10 | int first, second; 11 | Pair(int a, int b){ 12 | first = a; 13 | second = b; 14 | } 15 | } 16 | public static void main(String[] args){ 17 | Scanner scn = new Scanner(System.in); 18 | int n = scn.nextInt(), m = scn.nextInt(); 19 | 20 | 21 | int[][] a = new int[n][m]; 22 | int[][] dist = new int[n][m]; 23 | Queue Q = new LinkedList<>(); 24 | 25 | int[] dx = {1, -1, 0, 0}; 26 | int[] dy = {0, 0, 1, -1}; 27 | 28 | for (int i = 0; i < n; i++) { 29 | for (int j = 0; j < m; j++) { 30 | a[i][j] = scn.nextInt(); 31 | dist[i][j] = Integer.MAX_VALUE; 32 | if (i == 0 && a[i][j] != 0) { 33 | Q.add(new Pair(i, j)); 34 | dist[i][j] = 0; 35 | } 36 | } 37 | } 38 | 39 | while (!Q.isEmpty()) { 40 | int x = Q.peek().first; 41 | int y = Q.peek().second; 42 | Q.remove(); 43 | 44 | if (x == n - 1) { 45 | break; 46 | } 47 | 48 | for (int i = 0; i < 4; i++) { 49 | int xx = x + dx[i]; 50 | int yy = y + dy[i]; 51 | 52 | if (xx >= 0 && xx < n && yy >= 0 && yy < m && dist[xx][yy] == Integer.MAX_VALUE && a[xx][yy] == 1) { 53 | Q.add(new Pair(xx,yy)); 54 | dist[xx][yy] = dist[x][y] + 1; 55 | } 56 | 57 | } 58 | 59 | } 60 | 61 | for (int i = 0; i < n; i++) { 62 | for (int j = 0; j < m; j++) { 63 | System.out.print(dist[i][j] + " "); 64 | } 65 | System.out.println(); 66 | } 67 | 68 | int minimum_distance = Integer.MAX_VALUE; 69 | 70 | for (int j = 0; j < m; j++) { 71 | minimum_distance = Math.min(minimum_distance, dist[n - 1][j]); 72 | } 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # graph-algorithms-for-competitive-coding 2 | Graph Algorithms Repository for Coding Minutes Course. 3 | 4 | 5 | This is the repository for Graph Algorithms Course for Competitive Coding. 6 | Created by : Prateek Narang, Apaar Kamal, Coding Minutes 7 | 8 | Checkout the Complete Video Course - 9 | [Graph Algorithms for Competitive Coding Master Course](https://codingminutes.com/graph-algorithms.html) 10 | 11 | [![Graph Algorithms](https://codingminutes.com/imgs/Graphs.jpg)](https://www.youtube.com/watch?v=vxK8rbge9uY) 12 | --------------------------------------------------------------------------------