Graphs

The notes

Introduction and components

  • Vertex (node): points, objects
  • Edge (connection): lines linking vertices
  • A graph is a collection of vertices and edges
  • A graph is a non-linear data structure
  • Degree: number of connections, e.g. for B it is 3
  • Path: sequence of edges
  • Cycle: closed loop (e.g. A-B-C-A)

Types of graphs

  • Undirected graph: e.g. friends; A-B is the same as B-A
  • Directed graph (digraph): e.g. following; A to B differs from B to A
  • Weighted graph: costs or values on edges, e.g. distances 5 km, 10 km
  • Unweighted graph: edges carry no values
  • Connected graph: there is a path between all node pairs
  • Disconnected graph (no cycles, e.g. a simple tree or DAG)

Graph representations

1. Adjacency matrix (2D array)

  • Easy to implement
  • Space-efficient for dense graphs

2. Adjacency list (array of lists)

  • Efficient for sparse graphs
  • Less memory

Common operations

  • Add vertex
  • Remove edge
  • Get neighbors
  • Traversal (e.g. DFS, BFS)
  • Shortest path (e.g. Dijkstra hint)

Applications

  • Social networks
  • Web pages
  • Road maps
  • Routing algorithms
  • Recommended systems

Data structures deck

  1. 1. Linear vs non-linear
  2. 2. Arrays
  3. 3. Hashmaps
  4. 4. Stacks
  5. 5. Queue
  6. 6. Linked list
  7. 7. Binary tree
  8. 8. BST
  9. 9. Graphs
  10. 10. Heaps

Watch the lesson

Data structures, Lesson 24