Graph Types:

  • Undirected Graph: Edges have no direction - relationships are bidirectional (e.g., friendships on Facebook)
  • Directed Graph (Digraph): Edges have direction - relationships go one way (e.g., Twitter follows, web links)
  • Weighted Graph: Edges have values/costs (e.g., distances between cities, connection strength)
  • Cyclic Graph: Contains at least one cycle - you can return to a starting node by following edges

Real-World Examples:

Social Networks

People are nodes, friendships/follows are edges. Find mutual friends, suggest connections, measure influence.

Maps & Navigation

Cities are nodes, roads are weighted edges. Find shortest paths, optimize routes, plan trips.

Recommendation Systems

Users and items as nodes, edges show preferences. Recommend movies, products, or content based on connections.

Web & Internet

Web pages are nodes, hyperlinks are directed edges. PageRank algorithm, web crawling, SEO.

// Common Graph Algorithms:

// 1. Breadth-First Search (BFS) - Explore level by level
function BFS(graph, start):
    queue = [start]
    visited = new Set([start])
    while queue is not empty:
        node = queue.dequeue()
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.enqueue(neighbor)

// 2. Depth-First Search (DFS) - Explore as deep as possible
function DFS(graph, node, visited = new Set()):
    visited.add(node)
    for neighbor in graph[node]:
        if neighbor not in visited:
            DFS(graph, neighbor, visited)

// 3. Dijkstra's Algorithm - Find shortest path in weighted graph
function dijkstra(graph, start):
    distances = {node: Infinity for all nodes}
    distances[start] = 0
    pq = PriorityQueue()
    pq.add(start, 0)

    while pq is not empty:
        current = pq.extractMin()
        for neighbor, weight in graph[current]:
            distance = distances[current] + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                pq.add(neighbor, distance)

    return distances

Graph Properties & Concepts:

Connected Graph: There's a path between every pair of nodes

Complete Graph: Every node is connected to every other node

Tree: Connected graph with no cycles (N nodes, N-1 edges)

Bipartite Graph: Nodes can be divided into two groups where edges only connect nodes from different groups

Shortest Path: Path with minimum total edge weight between two nodes

Strongly Connected (Directed): Every node can reach every other node