YouTip LogoYouTip

Dsa Graph

Graph Structures | Tutorial

\\\\n\\\\n

Graph Theory Structures

\\\\n\\\\n

In computer science, graphs are widely used to simulate social networks (users are nodes, friend relationships are edges), web links (webpages are nodes, hyperlinks are edges), communication networks, and even path planning problems.

\\\\n\\\\n

Graphs are like a social network relationship map:

\\\\n\\\\n
    \\\\n
  • Nodes (Vertices): Every person in the social network
  • \\\\n
  • Edges: Relationships between people (friends, follows, etc.)
  • \\\\n
  • Weights: Strength of the relationship (intimacy, interaction frequency, etc.)
  • \\\\n
\\\\n\\\\n

Imagine the transportation network of your city: various locations (such as home, school, shopping mall) are points, and the roads connecting these locations are lines. A Graph is the mathematical abstraction of this point-and-line relationship; it is a data structure used to represent complex relationships between entities.

\\\\n\\\\n

Real-life Examples:

\\\\n\\\\n
    \\\\n
  • Maps: Cities are nodes, roads are edges, distance is weight
  • \\\\n
  • Circuits: Components are nodes, wires are edges, resistance is weight
  • \\\\n
  • Internet: Websites are nodes, links are edges, traffic is weight
  • \\\\n
  • Transportation Networks: Stations are nodes, routes are edges, fare is weight
  • \\\\n
\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n
ScenarioOther StructuresGraph Structure
Social RelationshipsDifficult to express complex relationshipsNaturally expresses many-to-many relationships
Path PlanningRequires complex data structuresIntuitively represents networks and paths
Dependency RelationshipsDifficult to represent cyclic dependenciesEasily handles complex dependencies
Network AnalysisCannot express network topologyPerfectly describes network structure
\\\\n\\\\n
\\\\n\\\\n

Basic Terminology of Graphs

\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n
TermDefinitionReal-life AnalogySymbolic Representation
VertexThe basic unit in a graphA person in a social networkV, u, v
EdgeA line connecting two verticesThe relationship between two peopleE, (u,v)
DegreeThe number of edges connected to a vertexThe number of friends a person hasdeg(v)
PathA sequence of verticesA route from A to Bv₁→v₂→…→vβ‚™
CycleA path where the start and end points are the sameLeaving home and eventually returning homev₁→v₂→…→v₁
Connected GraphThere is a path between any two pointsEveryone can contact each other
WeightNumerical attribute of an edgeDistance between two citiesw(u,v)
\\\\n\\\\n

Classification of Graphs

\\\\n\\\\nImage 1\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n
Classification CriteriaTypeCharacteristicsApplication Scenarios
DirectionalityUndirected GraphEdges have no directionFriendship relationships, road networks
Directed GraphEdges have directionFollow relationships, workflows
WeightUnweighted GraphAll edges have the same weightSocial network relationships
Weighted GraphEdges have different weightsMap distances, network traffic
ConnectivityConnected GraphAny two points are reachableTransportation networks
Disconnected GraphIsolated points existSocial groups
CycleAcyclic GraphNo loopsTask dependencies, family trees
Cyclic GraphContains loopsRoad networks
\\\\n\\\\n

Representation Methods of Graphs

\\\\n\\\\n

Adjacency Matrix

\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n
FeatureDescriptionTime ComplexitySpace Complexity
Storage Method2D Matrix
Check Edge Existencematrix != 0O(1)
Add Edgematrix = weightO(1)
Delete Edgematrix = 0O(1)
Traverse Adjacent PointsScan a row/columnO(V)
Space UsageVΓ—V MatrixO(VΒ²)
\\\\n\\\\n

Adjacency List

\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n
FeatureDescriptionTime ComplexitySpace Complexity
Storage MethodArray + Linked List
Check Edge ExistenceSearch in linked listO(deg(v))
Add EdgeAdd to linked listO(1)
Delete EdgeDelete from linked listO(deg(v))
Traverse Adjacent PointsTraverse linked listO(deg(v))
Space UsageVertex Array + Edge Linked ListO(V+E)
\\\\n\\\\n

Basic Concepts of Graphs

\\\\n\\\\n

A graph G consists of two sets:

\\\\n\\\\n
    \\\\n
  • Vertex Set V (Vertex Set): The set of all points in the graph.
  • \\\\n
  • Edge Set E (Edge Set): The set of lines connecting these points. An edge is represented by the two vertices (u, v) it connects.
  • \\\\n
\\\\n\\\\n

Example

\\\\n\\\\n
# A Simple Graph Example: Representing Social Network Friendships with Dictionary\\\\n\\\\n# Vertex: Alice, Bob, Charlie, Diana\\\\n\\\\n# Edge: represents the friend relationship between them\\\\n\\\\nsocial_graph ={\\\\n\\\\n'Alice': ['Bob','Charlie'],# Alice is Bob and Charlie friend\\\\n\\\\n'Bob': ['Alice','Charlie','Diana'],\\\\n\\\\n'Charlie': ['Alice','Bob'],\\\\n\\\\n'Diana': ['Bob']\\\\n\\\\n}\\\\n\\\\nprint(f"Vertex (User): {list(social_graph.keys())}")\\\\n\\\\nprint(f"Alice friend (Edge): {social_graph['Alice']}")\\\\n
\\\\n\\\\n

Output:

\\\\n\\\\n

Vertex (User): ['Alice', 'Bob', 'Charlie', 'Diana']Alice friend (Edge): ['Bob', 'Charlie']

\\\\n\\\\n
\\\\n\\\\n

Graph Classification and Important Concepts

\\\\n\\\\n

Graphs can be divided into various types based on the characteristics of their edges. Understanding these is the foundation of mastering graph theory.

\\\\n\\\\n

Undirected Graph vs Directed Graph

\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n
TypeCharacteristics of Edges (Edge)Real-life AnalogyExample
Undirected GraphEdges have no direction, (A, B) indicates A and B are mutually connected.Mutual Friendship: If Alice is Bob's friend, then Bob must also be Alice's friend.Friendship relationships in social networks, connections in circuits.
Directed GraphEdges have direction, A -> B indicates a one-way connection from A to B.Weibo Follow: You can follow someone, but they may not necessarily follow you back.Webpage hyperlinks, task dependencies, one-way streets.
\\\\n\\\\nImage 2\\\\n\\\\n

Weighted Graph

\\\\n\\\\n

In a weighted graph, every edge is assigned a numerical value (weight), which can represent distance, cost, time, or relationship strength.

\\\\n\\\\n

Example

\\\\n\\\\n
# A Weighted Graph Representing Distances Between Cities (Adjacency List Form)\\\\n\\\\n weighted_graph ={\\\\n\\\\n'Beijing': {('Shanghai',1200),('Tianjin',100)},# BeijingtoShanghaidistance 1200, toTianjin distance 100\\\\n\\\\n'Shanghai': {('Beijing',1200),('Hangzhou',200)},\\\\n\\\\n'Tianjin': {('Beijing',100)},\\\\n\\\\n'Hangzhou': {('Shanghai',200)}\\\\n\\\\n}\\\\n
\\\\n\\\\n

Key Terms

\\\\n\\\\n
    \\\\n
  • Degree: The number of edges connected to a vertex. In directed graphs, it is divided into In-degree (number of edges pointing to the vertex) and Out-degree (number of edges pointing out from the vertex).
  • \\\\n
  • Path: A sequence of edges passed through from one vertex to another. e.g., A -> B -> C.
  • \\\\n
  • Cycle: A path where the start and end points are the same vertex.
  • \\\\n
  • Connected Graph: In an undirected graph, there exists a path between any two vertices.
  • \\\\n
  • Strongly Connected Graph: In a directed graph, there exists a bidirectional path between any two vertices.
  • \\\\n
\\\\n\\\\n
\\\\n\\\\n

Storage Methods of Graphs

\\\\n\\\\n

How to represent a graph in a computer? There are mainly two mainstream methods.

\\\\n\\\\n

Adjacency Matrix

\\\\n\\\\n

Use a 2D array (matrix) matrix to represent the graph. The value of matrix represents the status of the edge from vertex i to vertex j.

\\\\n\\\\n
    \\\\n
  • For undirected graphs, the matrix is symmetric.
  • \\\\n
  • For weighted graphs, the matrix values store weights (use special values like 0 or ∞ to indicate no edge).
  • \\\\n
  • Advantage: Checking if there is an edge between any two vertices is very fast (O(1)).
  • \\\\n
  • Disadvantage: Occupies large space (O(V^2)), wasting space for "sparse graphs" with fewer edges.
  • \\\\n
\\\\n\\\\n

Example

\\\\n\\\\n
# Representing an Undirected Graph Using Adjacency Matrix\\\\n\\\\n# Vertex: 0-A, 1-B, 2-C\\\\n\\\\n# Edge: A-B, A-C\\\\n\\\\nV =3# Number of Vertices\\\\n\\\\n adj_matrix =[ * V for _ in range(V)]\\\\n\\\\n# add Edge A-B (0-1)\\\\n\\\\n adj_matrix=1\\\\n\\\\n adj_matrix=1# Undirected Graph Requires Setting Symmetric Positions\\\\n\\\\n# add Edge A-C (0-2)\\\\n\\\\n adj_matrix=1\\\\n\\\\n adj_matrix=1\\\\n\\\\nprint("Adjacency Matrix:")\\\\n\\\\nfor row in adj_matrix:\\\\n\\\\nprint(row)\\\\n\\\\n# Output:\\\\n\\\\n# [0, 1, 1]\\\\n\\\\n# [1, 0, 0]\\\\n\\\\n# [1, 0, 0]\\\\n
\\\\n\\\\n

Adjacency List

\\\\n\\\\n

Maintain a list (linked list, array, etc.) for each vertex, recording all vertices (and weights) directly connected to it.

\\\\n\\\\n
    \\\\n
  • Advantage: High space efficiency (O(V + E)), especially suitable for sparse graphs. Can quickly find all neighbors of a vertex.
  • \\\\n
  • Disadvantage: Slower to check if there is an edge between any two vertices (O(degree(V))).
  • \\\\n
\\\\n\\\\n

Example

\\\\n\\\\n
# Representing the Same Undirected Graph Using Adjacency List (Dictionary + List)\\\\n\\\\n adj_list ={\\\\n\\\\n'A': ['B','C'],# A connects B and C\\\\n\\\\n'B': ['A'],# B Connected to A\\\\n\\\\n'C': ['A']# C Connected to A\\\\n\\\\n}\\\\n\\\\nprint("Adjacency List:")\\\\n\\\\nfor vertex, neighbors in adj_list.items():\\\\n\\\\nprint(f"{vertex}: {neighbors}")\\\\n
\\\\n\\\\n
\\\\n\\\\n

Graph Traversal Algorithms

\\\\n\\\\n

Traversal is the foundation of graph algorithms, meaning systematically visiting every vertex in the graph.

\\\\n\\\\n

There are mainly two strategies:

\\\\n\\\\n

Breadth-First Search

\\\\n\\\\n

Breadth-First Search (BFS) spreads like "water waves", starting from the origin, first visiting all direct neighbors, then neighbors' neighbors, and so on. It uses a Queue to implement.

\\\\n\\\\n

Algorithm Steps:

\\\\n\\\\n
    \\\\n
  1. Add the starting point to the queue and mark it as visited.
  2. \\\\n
  3. While the queue is not empty:\\\\n<
← Dsa Greedy AlgorithmDsa Hash Table β†’