Home

Graph Data Structure

What is a Graph?

A graph is a non-linear data structure consisting of nodes (or vertices) and edges that connect pairs of nodes. Graphs are used to represent networks, such as social networks, communication networks, and more. They can be directed or undirected, weighted or unweighted.

Basic Visualization

A
B

Common Operations

Adding an Edge

function addEdge(graph, node1, node2):
    if node1 not in graph:
        graph[node1] = []
    if node2 not in graph:
        graph[node2] = []
    graph[node1].append(node2)
    graph[node2].append(node1)  // For undirected graph

Depth-First Search (DFS)

function dfs(graph, start, visited=set()):
    if start not in visited:
        print(start)
        visited.add(start)
        for neighbor in graph[start]:
            if neighbor not in visited:
                dfs(graph, neighbor, visited)

Breadth-First Search (BFS)

function bfs(graph, start):
    queue = [start]
    visited = set([start])
    while queue:
        vertex = queue.pop(0)
        print(vertex)
        for neighbor in graph[vertex]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)