Graph Data Structure And Algorithms - GeeksforGeeks

18 Jun, 2022
Data Structure and Algorithms CoursePractice Problems on GraphsRecent Articles on Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as,
A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.
A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.
In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}.
Graphs are used to solve many real-life problems. Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a vertex(or node). Each node is a structure and contains information like person id, name, gender, locale etc.
Introduction, DFS and BFS
Graph Cycle
Topological Sorting
Minimum Spanning Tree
BackTracking
Shortest Paths
Connectivity
Maximum Flow
STL Implementation of Algorithms
Hard Problems
Misc
Quick Links
Graph and its representationsBreadth First Traversal for a GraphDepth First Traversal for a GraphApplications of Depth First SearchApplications of Breadth First TraversalGraph representations using set and hashFind Mother Vertex in a GraphTransitive Closure of a Graph using DFSFind K cores of an undirected GraphIterative Depth First SearchCount the number of nodes at given level in a tree using BFSCount all possible paths between two verticesMinimum initial vertices to traverse whole matrix with given conditionsShortest path to reach one prime to other by changing single digit at a timeWater Jug problem using BFSCount number of trees in a forestBFS using vectors & queue as per the algorithm of CLRSLevel of Each node in a Tree from source nodeConstruct binary palindrome by repeated appending and trimmingTranspose graphPath in a Rectangle with CirclesHeight of a generic tree from parent arrayBFS using STL for competitive codingDFS for a n-ary tree (acyclic graph) represented as adjacency listMaximum number of edges to be added to a tree so that it stays a Bipartite graphA Peterson Graph ProblemImplementation of Graph in JavaScriptPrint all paths from a given source to a destination using BFSMinimum number of edges between two vertices of a GraphCount nodes within K-distance from all nodes in a setBidirectional SearchMinimum edge reversals to make a rootBFS for Disconnected GraphMove weighting scale alternate under given constraintsBest First Search (Informed Search)Number of pair of positions in matrix which are not accessibleMaximum product of two non-intersecting paths in a treeDelete Edge to minimize subtree sum differenceFind the minimum number of moves needed to move from one cell of matrix to anotherMinimum steps to reach target by a Knight | Set 1Minimum number of operation required to convert number x into yMinimum steps to reach end of array under constraintsFind the smallest binary digit multiple of given numberRoots of a tree which give minimum heightStepping NumbersClone an Undirected GraphSum of the minimum elements in all connected components of an undirected graphCheck if two nodes are on same path in a treeA matrix probability questionFind length of the largest region in Boolean MatrixIterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Graph and its representations
Breadth First Traversal for a Graph
Depth First Traversal for a Graph
Applications of Depth First Search
Applications of Breadth First Traversal
Graph representations using set and hash
Find Mother Vertex in a Graph
Transitive Closure of a Graph using DFS
Find K cores of an undirected Graph
Iterative Depth First Search
Count the number of nodes at given level in a tree using BFS
Count all possible paths between two vertices
Minimum initial vertices to traverse whole matrix with given conditions
Shortest path to reach one prime to other by changing single digit at a time
Water Jug problem using BFS
Count number of trees in a forest
BFS using vectors & queue as per the algorithm of CLRS
Level of Each node in a Tree from source node
Construct binary palindrome by repeated appending and trimming
Transpose graph
Path in a Rectangle with Circles
Height of a generic tree from parent array
BFS using STL for competitive coding
DFS for a n-ary tree (acyclic graph) represented as adjacency list
Maximum number of edges to be added to a tree so that it stays a Bipartite graph
A Peterson Graph Problem
Implementation of Graph in JavaScript
Print all paths from a given source to a destination using BFS
Minimum number of edges between two vertices of a Graph
Count nodes within K-distance from all nodes in a set
Bidirectional Search
Minimum edge reversals to make a root
BFS for Disconnected Graph
Move weighting scale alternate under given constraints
Best First Search (Informed Search)
Number of pair of positions in matrix which are not accessible
Maximum product of two non-intersecting paths in a tree
Delete Edge to minimize subtree sum difference
Find the minimum number of moves needed to move from one cell of matrix to another
Minimum steps to reach target by a Knight | Set 1
Minimum number of operation required to convert number x into y
Minimum steps to reach end of array under constraints
Find the smallest binary digit multiple of given number
Roots of a tree which give minimum height
Stepping Numbers
Clone an Undirected Graph
Sum of the minimum elements in all connected components of an undirected graph
Check if two nodes are on same path in a tree
A matrix probability question
Find length of the largest region in Boolean Matrix
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Graph Cycle :
Detect Cycle in a Directed GraphDetect cycle in an undirected graphDetect cycle in a direct graph using colorsAssign directions to edges so that the directed graph remains acyclicDetect a negative cycle in a Graph | (Bellman Ford)Cycles of length n in an undirected and connected graphDetecting negative cycle using Floyd WarshallCheck if there is a cycle with odd weight sum in an undirected graphCheck if a graphs has a cycle of odd lengthClone a Directed Acyclic GraphCheck loop in array according to given constraintsDisjoint Set (Or Union-Find) | Set 1Union-Find Algorithm | Set 2Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)Magical Indices in an array
Detect Cycle in a Directed Graph
Detect cycle in an undirected graph
Detect cycle in a direct graph using colors
Assign directions to edges so that the directed graph remains acyclic
Detect a negative cycle in a Graph | (Bellman Ford)
Cycles of length n in an undirected and connected graph
Detecting negative cycle using Floyd Warshall
Check if there is a cycle with odd weight sum in an undirected graph
Check if a graphs has a cycle of odd length
Clone a Directed Acyclic Graph
Check loop in array according to given constraints
Disjoint Set (Or Union-Find) | Set 1
Union-Find Algorithm | Set 2
Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
Magical Indices in an array
Topological Sorting :
Topological SortingAll topological sorts of a Directed Acyclic GraphKahn’s Algorithm for Topological SortingMaximum edges that can be added to DAG so that is remains DAGLongest path between any pair of verticesLongest Path in a Directed Acyclic GraphLongest Path in a Directed Acyclic Graph | Set 2Topological Sort of a graph using departure time of vertexGiven a sorted dictionary of an alien language, find order of characters
Topological Sorting
All topological sorts of a Directed Acyclic Graph
Kahn’s Algorithm for Topological Sorting
Maximum edges that can be added to DAG so that is remains DAG
Longest path between any pair of vertices
Longest Path in a Directed Acyclic Graph
Longest Path in a Directed Acyclic Graph | Set 2
Topological Sort of a graph using departure time of vertex
Given a sorted dictionary of an alien language, find order of characters
Minimum Spanning Tree :
Prim’s Minimum Spanning Tree (MST))Applications of Minimum Spanning Tree ProblemPrim’s MST for Adjacency List RepresentationKruskal’s Minimum Spanning Tree AlgorithmBoruvka’s algorithm for Minimum Spanning TreeMinimum cost to connect all citiesSteiner TreeReverse Delete Algorithm for Minimum Spanning TreeTotal number of Spanning Trees in a GraphMinimum Product Spanning Tree
Prim’s Minimum Spanning Tree (MST))
Applications of Minimum Spanning Tree Problem
Prim’s MST for Adjacency List Representation
Kruskal’s Minimum Spanning Tree Algorithm
Boruvka’s algorithm for Minimum Spanning Tree
Minimum cost to connect all cities
Steiner Tree
Reverse Delete Algorithm for Minimum Spanning Tree
Total number of Spanning Trees in a Graph
Minimum Product Spanning Tree
BackTracking :
Find if there is a path of more than k length from a sourceTug of WarThe Knight-Tour ProblemRat in a Mazen-Queen’s Problemm Coloring ProblemHamiltonian CyclePermutation of numbers such that sum of two consecutive numbers is a perfect square
Find if there is a path of more than k length from a source
Tug of War
The Knight-Tour Problem
Rat in a Maze
n-Queen’s Problem
m Coloring Problem
Hamiltonian Cycle
Permutation of numbers such that sum of two consecutive numbers is a perfect square
Shortest Paths :
Dijkstra’s shortest path algorithmDijkstra’s Algorithm for Adjacency List RepresentationBellman–Ford AlgorithmFloyd Warshall AlgorithmJohnson’s algorithm for All-pairs shortest pathsShortest Path in Directed Acyclic GraphShortest path with exactly k edges in a directed and weighted graphDial’s AlgorithmPrinting paths in Dijsktra’s AlgorithmShortest path of a weighted graph where weight is 1 or 2Multistage Graph (Shortest Path)Shortest path in an unweighted graphMinimize the number of weakly connected nodesBetweenness Centrality (Centrality Measure)Comparison of Dijkstra’s and Floyd–Warshall algorithmsKarp’s minimum mean (or average) weight cycle algorithm0-1 BFS (Shortest Path in a Binary Weight Graph)Find minimum weight cycle in an undirected graphMinimum Cost Path with Left, Right, Bottom and Up moves allowedMinimum edges to reverse to make path from a src to a destFind Shortest distance from a guard in a Bank
Dijkstra’s shortest path algorithm
Dijkstra’s Algorithm for Adjacency List Representation
Bellman–Ford Algorithm
Floyd Warshall Algorithm
Johnson’s algorithm for All-pairs shortest paths
Shortest Path in Directed Acyclic Graph
Shortest path with exactly k edges in a directed and weighted graph
Dial’s Algorithm
Printing paths in Dijsktra’s Algorithm
Shortest path of a weighted graph where weight is 1 or 2
Multistage Graph (Shortest Path)
Shortest path in an unweighted graph
Minimize the number of weakly connected nodes
Betweenness Centrality (Centrality Measure)
Comparison of Dijkstra’s and Floyd–Warshall algorithms
Karp’s minimum mean (or average) weight cycle algorithm
0-1 BFS (Shortest Path in a Binary Weight Graph)
Find minimum weight cycle in an undirected graph
Minimum Cost Path with Left, Right, Bottom and Up moves allowed
Minimum edges to reverse to make path from a src to a dest
Find Shortest distance from a guard in a Bank
Connectivity :
Find if there is a path between two vertices in a directed graphConnectivity in a directed graphArticulation Points (or Cut Vertices) in a GraphBiconnected ComponentsBiconnected graphBridges in a graphEulerian path and circuitFleury’s Algorithm for printing Eulerian Path or CircuitStrongly Connected ComponentsTransitive closure of a graphFind the number of islandsFind the number of Islands | Set 2 (Using Disjoint Set)Count all possible walks from a source to a destination with exactly k edgesEuler Circuit in a Directed GraphCount the number of non-reachable nodesFind the Degree of a Particular vertex in a GraphCheck if a given graph is tree or notMinimum edges required to add to make Euler CircuitEulerian Path in undirected graphFind if there is a path of more than k lengthLength of shortest chain to reach the target wordPrint all paths from a given source to destinationFind minimum cost to reach destination using trainFind if an array of strings can be chained to form a circle | Set 1Find if an array of strings can be chained to form a circle | Set 2Tarjan’s Algorithm to find strongly connected ComponentsNumber of loops of size k starting from a specific nodePaths to travel each nodes using each edge (Seven Bridges of Königsberg)Number of cyclic elements in an array where we can jump according to valueNumber of groups formed in a graph of friendsMinimum cost to connect weighted nodes represented as arrayCount single node isolated sub-graphs in a disconnected graphCalculate number of nodes between two vertices in an acyclic Graph by Disjoint Union methodDynamic Connectivity | Set 1 (Incremental)Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)Check if removing a given edge disconnects a graphFind all reachable nodes from every node present in a given setConnected Components in an undirected graphk’th heaviest adjacent node in a graph where each vertex has weight
Find if there is a path between two vertices in a directed graph
Connectivity in a directed graph
Articulation Points (or Cut Vertices) in a Graph
Biconnected Components
Biconnected graph
Bridges in a graph
Eulerian path and circuit
Fleury’s Algorithm for printing Eulerian Path or Circuit
Strongly Connected Components
Transitive closure of a graph
Find the number of islands
Find the number of Islands | Set 2 (Using Disjoint Set)
Count all possible walks from a source to a destination with exactly k edges
Euler Circuit in a Directed Graph
Count the number of non-reachable nodes
Find the Degree of a Particular vertex in a Graph
Check if a given graph is tree or not
Minimum edges required to add to make Euler Circuit
Eulerian Path in undirected graph
Find if there is a path of more than k length
Length of shortest chain to reach the target word
Print all paths from a given source to destination
Find minimum cost to reach destination using train
Find if an array of strings can be chained to form a circle | Set 1
Find if an array of strings can be chained to form a circle | Set 2
Tarjan’s Algorithm to find strongly connected Components
Number of loops of size k starting from a specific node
Paths to travel each nodes using each edge (Seven Bridges of Königsberg)
Number of cyclic elements in an array where we can jump according to value
Number of groups formed in a graph of friends
Minimum cost to connect weighted nodes represented as array
Count single node isolated sub-graphs in a disconnected graph
Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
Dynamic Connectivity | Set 1 (Incremental)
Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
Check if removing a given edge disconnects a graph
Find all reachable nodes from every node present in a given set
Connected Components in an undirected graph
k’th heaviest adjacent node in a graph where each vertex has weight
Maximum Flow :
Ford-Fulkerson Algorithm for Maximum Flow ProblemFind maximum number of edge disjoint paths between two verticesFind minimum s-t cut in a flow networkMaximum Bipartite MatchingChannel Assignment ProblemPush Relabel- Set 1-IntroductionPush Relabel- Set 2- ImplementationKarger’s Algorithm- Set 1- Introduction and ImplementationKarger’s Algorithm- Set 2 – Analysis and ApplicationsDinic’s algorithm for Maximum FlowMax Flow Problem Introduction
Ford-Fulkerson Algorithm for Maximum Flow Problem
Find maximum number of edge disjoint paths between two vertices
Find minimum s-t cut in a flow network
Maximum Bipartite Matching
Channel Assignment Problem
Push Relabel- Set 1-Introduction
Push Relabel- Set 2- Implementation
Karger’s Algorithm- Set 1- Introduction and Implementation
Karger’s Algorithm- Set 2 – Analysis and Applications
Dinic’s algorithm for Maximum Flow
Max Flow Problem Introduction
STL Implementation of Algorithms :
Kruskal’s Minimum Spanning Tree using STL in C++Prim’s Algorithm using Priority Queue STLDijkstra’s Shortest Path Algorithm using STLDijkstra’s Shortest Path Algorithm using set in STLGraph implementation using STL for competitive programming | Set 2 (Weighted graph)
Kruskal’s Minimum Spanning Tree using STL in C++
Prim’s Algorithm using Priority Queue STL
Dijkstra’s Shortest Path Algorithm using STL
Dijkstra’s Shortest Path Algorithm using set in STL
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
Hard Problems :
Graph Coloring (Introduction and Applications)Greedy Algorithm for Graph ColoringTraveling Salesman Problem (TSP) ImplementationTravelling Salesman Problem (Naive and Dynamic Programming)Travelling Salesman Problem (Approximate using MST)Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)K Centers Problem | Set 1 (Greedy Approximate Algorithm)Erdos Renyl Model (for generating Random Graphs)Clustering Coefficient in Graph TheoryChinese Postman or Route Inspection | Set 1 (introduction)Hierholzer’s Algorithm for directed graph
Graph Coloring (Introduction and Applications)
Greedy Algorithm for Graph Coloring
Traveling Salesman Problem (TSP) Implementation
Travelling Salesman Problem (Naive and Dynamic Programming)
Travelling Salesman Problem (Approximate using MST)
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Erdos Renyl Model (for generating Random Graphs)
Clustering Coefficient in Graph Theory
Chinese Postman or Route Inspection | Set 1 (introduction)
Hierholzer’s Algorithm for directed graph
Misc :
Number of triangles in an undirected GraphNumber of triangles in directed and undirected GraphCheck whether a given graph is Bipartite or notSnake and Ladder ProblemMinimize Cash Flow among a given set of friends who have borrowed money from each otherBoggle (Find all possible words in a board of characters)Hopcroft Karp Algorithm for Maximum Matching-IntroductionHopcroft Karp Algorithm for Maximum Matching-ImplementationMinimum Time to rot all orangesFind same contents in a list of contactsHypercube GraphCheck for star graphOptimal read list for a given number of daysPrint all jumping numbers smaller than or equal to a given valueFibonacci Cube GraphBarabasi Albert Graph (for Scale Free Models)Construct a graph from given degrees of all verticesDegree Centrality (Centrality Measure)Katz Centrality (Centrality Measure)Mathematics | Graph theory practice questions2-Satisfiability (2-SAT) ProblemDetermine whether a universal sink exists in a directed graphNumber of sink nodes in a graphLargest subset of Graph vertices with edges of 2 or more colorsNetworkX : Python software package for study of complex networksGenerate a graph using Dictionary in PythonCount number of edges in an undirected graphTwo Clique Problem (Check if Graph can be divided in two Cliques)Check whether given degrees of vertices represent a Graph or TreeFinding minimum vertex cover size of a graph using binary searchStable Marriage ProblemSum of dependencies in a graph
Number of triangles in an undirected Graph
Number of triangles in directed and undirected Graph
Check whether a given graph is Bipartite or not
Snake and Ladder Problem
Minimize Cash Flow among a given set of friends who have borrowed money from each other
Boggle (Find all possible words in a board of characters)
Hopcroft Karp Algorithm for Maximum Matching-Introduction
Hopcroft Karp Algorithm for Maximum Matching-Implementation
Minimum Time to rot all oranges
Find same contents in a list of contacts
Hypercube Graph
Check for star graph
Optimal read list for a given number of days
Print all jumping numbers smaller than or equal to a given value
Fibonacci Cube Graph
Barabasi Albert Graph (for Scale Free Models)
Construct a graph from given degrees of all vertices
Degree Centrality (Centrality Measure)
Katz Centrality (Centrality Measure)
Mathematics | Graph theory practice questions
2-Satisfiability (2-SAT) Problem
Determine whether a universal sink exists in a directed graph
Number of sink nodes in a graph
Largest subset of Graph vertices with edges of 2 or more colors
NetworkX : Python software package for study of complex networks
Generate a graph using Dictionary in Python
Count number of edges in an undirected graph
Two Clique Problem (Check if Graph can be divided in two Cliques)
Check whether given degrees of vertices represent a Graph or Tree
Finding minimum vertex cover size of a graph using binary search
Stable Marriage Problem
Sum of dependencies in a graph
Quick Links :
Top 10 Interview Questions on Depth First Search (DFS)
Some interesting shortest path questions
Quizzes on Graph Traversal
Quizzes on Graph Shortest Path
Quizzes on Graph Minimum Spanning Tree
Quizzes on Graphs
Practice Problems on Graphs
Videos on Graphs
1. Language Foundation Courses [C++ / JAVA / Python ]Learn any programming language from scratch and understand all its fundamentals concepts for a strong programming foundation in the easiest possible manner with help of GeeksforGeeks Language Foundation Courses – Java Foundation | Python Foundation | C++ Foundation
2. Geeks Classes LiveGet interview-centric live online classes on Data Structure and Algorithms from any geographical location to learn and master DSA concepts for enhancing your problem-solving & programming skills and to crack the interview of any product-based company – Geeks Classes: Live Session
3. Complete Interview PreparationGet fulfilled all your interview preparation needs at a single place with the Complete Interview Preparation Course that provides you all the required stuff to prepare for any product-based, service-based, or start-up company at the most affordable prices.
4. DSA Self PacedStart learning Data Structures and Algorithms to prepare for the interviews of top IT giants like Microsoft, Amazon, Adobe, etc. with DSA Self-Paced Course where you will get to learn and master DSA from basic to advanced level and that too at your own pace and convenience.
5. Company Specific Courses – Amazon, Microsoft, TCS & WiproCrack the interview of any product-based giant company by specifically preparing with the questions that these companies usually ask in their coding interview round. Refer GeeksforGeeks Company Specific Courses: Amazon SDE Test Series, etc.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Floyd’s Cycle Finding Algorithm
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Git in VS Code?
Git - Difference Between Git Fetch and Git Pull
ReactJS useNavigate() Hook
SDE SHEET - A Complete Guide for SDE Preparation