Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Graph — Introduction

What is a Graph?

A graph G = (V, E) is a data structure consisting of a set of vertices (nodes) V and a set of edges E connecting pairs of vertices. Graphs model real-world relationships: social networks, road maps, computer networks, dependency trees, and more.

TypeDescriptionExample
UndirectedEdges have no directionFacebook friendships
Directed (Digraph)Edges have direction (A→B ≠ B→A)Twitter follows, web links
WeightedEdges have a cost/weightRoad distances, network latency
UnweightedAll edges have equal weightSocial connections
CyclicContains at least one cycleRoad network
Acyclic (DAG)No cyclesTask scheduling, Git commits

Graph Representations

RepresentationSpaceAdd EdgeCheck EdgeBest for
Adjacency MatrixO(V²)O(1)O(1)Dense graphs
Adjacency ListO(V + E)O(1)O(degree)Sparse graphs
Edge ListO(E)O(1)O(E)Kruskal's MST
Graph Representations — Adjacency List and Matrix
import java.util.*;

public class Graph {

    // Adjacency List representation — O(V + E) space
    static class GraphList {
        int V;
        List<List<Integer>> adj;

        GraphList(int v) {
            V = v;
            adj = new ArrayList<>();
            for (int i = 0; i < v; i++) adj.add(new ArrayList<>());
        }

        void addEdge(int u, int v) {
            adj.get(u).add(v);
            adj.get(v).add(u);  // undirected: add both directions
        }

        void printGraph() {
            for (int i = 0; i < V; i++) {
                System.out.print(i + " → " + adj.get(i));
                System.out.println();
            }
        }
    }

    // Adjacency Matrix representation — O(V²) space
    static class GraphMatrix {
        int V;
        int[][] matrix;

        GraphMatrix(int v) {
            V = v;
            matrix = new int[v][v];
        }

        void addEdge(int u, int v) {
            matrix[u][v] = 1;
            matrix[v][u] = 1;  // undirected
        }

        void printMatrix() {
            System.out.print("  ");
            for (int i = 0; i < V; i++) System.out.print(i + " ");
            System.out.println();
            for (int i = 0; i < V; i++) {
                System.out.print(i + " ");
                for (int j = 0; j < V; j++) System.out.print(matrix[i][j] + " ");
                System.out.println();
            }
        }
    }

    public static void main(String[] args) {
        // Graph: 0-1, 0-2, 1-2, 1-3, 2-4
        GraphList gl = new GraphList(5);
        gl.addEdge(0, 1); gl.addEdge(0, 2);
        gl.addEdge(1, 2); gl.addEdge(1, 3); gl.addEdge(2, 4);
        System.out.println("Adjacency List:");
        gl.printGraph();

        GraphMatrix gm = new GraphMatrix(5);
        gm.addEdge(0, 1); gm.addEdge(0, 2);
        gm.addEdge(1, 2); gm.addEdge(1, 3); gm.addEdge(2, 4);
        System.out.println("\nAdjacency Matrix:");
        gm.printMatrix();
    }
}

Graph Terminology

TermDefinitionExample
Vertex (Node)A fundamental unit of a graphA city in a road map
EdgeA connection between two verticesA road between two cities
DegreeNumber of edges connected to a vertexCity with 3 roads has degree 3
PathSequence of vertices connected by edgesRoute from A to D via B, C
CycleA path that starts and ends at the same vertexA → B → C → A
Connected GraphEvery vertex is reachable from every otherAll cities connected by roads
Weighted GraphEdges have associated costs/weightsRoad distances
DAGDirected Acyclic Graph — no cyclesTask dependencies, Git commits
TreeConnected acyclic undirected graphFile system hierarchy
Spanning TreeTree that includes all vertices of a graphMinimum network connecting all cities

Graph Traversal Overview

Two fundamental ways to traverse a graph:

FeatureBFS (Breadth-First)DFS (Depth-First)
Data structureQueue (FIFO)Stack / Recursion
OrderLevel by levelDeep first, then backtrack
Shortest pathYes (unweighted)No
Cycle detectionYesYes
Time complexityO(V + E)O(V + E)
Space complexityO(V)O(V)

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.