Use Kahn's algorithm for topological sorting. With an adjacency list representation, count every vertex's indegree by scanning the edges. Put all zero-indegree vertices in a queue. Repeatedly remove one such vertex , append it to the output, and delete its outgoing edges by decrementing the stored indegree of each neighbour; enqueue a neighbour exactly when its count becomes zero.
The loop invariant is that stored counts are the indegrees in the unreported subgraph and the queue contains exactly its unreported zero-indegree vertices. A nonempty finite Directed acyclic graph always has such a vertex: otherwise following incoming edges would eventually repeat a vertex, creating a directed graph cycle. Thus the queue cannot become empty while any vertex remains.
For every original edge , cannot enter the output until that edge has been removed by outputting . Therefore
Each vertex enters and leaves the queue once, and every edge is scanned a constant number of times, giving time and auxiliary space beyond the adjacency lists. If given only an adjacency matrix, scanning neighbours instead takes time.
Depth-first search marks a vertex when first reached, then recursively explores each still-unvisited neighbour before returning. To cover the whole graph, restart from every vertex not reached by earlier searches:
visit(v):
    visited[v] = true
    for w in adjacency[v]:
        if not visited[w]:
            visit(w)

for v in V:
    if not visited[v]:
        visit(v)
For a directed graph, use outgoing neighbours; for an undirected graph, use both incidences of each edge. Each vertex is discovered once and each stored incidence is inspected once. Thus with adjacency lists the running time is and the visited information and recursion stack use space. An adjacency matrix representation instead requires scanning possible neighbours per visited vertex, giving time.
Use subset dynamic programming for a Hamiltonian path, with a Boolean dynamic programming state for each nonempty subset and . It is true exactly when there is a graph path using every vertex of once, using no other vertices, and ending at . The base and transition are
where is the adjacency matrix of a directed graph.
HamiltonianExists(A):
    initialize every D[S,v] to false
    for v in V:
        D[{v},v] = true
    for k = 2,...,n:
        for S subset of V with |S| = k:
            for v in S:
                D[S,v] = any(D[S-{v},u] and A[u,v]
                             for u in S-{v})
    return any(D[V,v] for v in V)
For correctness, a valid path ending at has some penultimate vertex ; removing yields exactly a path recorded by the corresponding predecessor state. Conversely, extending any true predecessor state by the edge produces a path visiting precisely once. Mathematical induction on proves the meaning of every state. Therefore the final disjunction is true exactly when a Hamiltonian path exists.
There are possible states and at most predecessor checks per state. More exactly, the full set of ordered predecessor checks has size for . With constant-time adjacency matrix access and ordinary subset-indexed table access,
The graph is normally assumed nonempty here. If the empty graph is admitted, return the chosen convention for its empty Hamiltonian path separately; it does not affect the bound.
Compute any topological sort using a standard algorithm, then check its consecutive entries in the adjacency matrix:
DAGHamiltonianPath(A):
    order = TopologicalSort(A)
    for j = 1,...,n-1:
        if not A[order[j],order[j+1]]:
            return "no Hamiltonian path"
    return order
If all checks pass, the returned ordering is a Hamiltonian path. If a check fails but a Hamiltonian path existed, part (d) would force the computed topological sort to equal the unique path order, whose consecutive edges all exist. This contradiction proves the negative answer correct.
A standard topological sort scans all matrix rows and therefore takes time with this input representation; the subsequent edge checks take . The answer is consequently time, with auxiliary storage beyond the input matrix. An bound for an adjacency list must not be substituted for the stipulated adjacency matrix bound.
Use an indexed priority queue of unsettled vertices, keyed by their tentative distances. Initialize the source to zero and other keys to . Each ExtractMin settles the currently closest vertex. Scan its outgoing edges; whenever edge relaxation improves a neighbour's tentative distance, update that neighbour with DecreaseKey. Already settled vertices need no further update, by the correctness of Dijkstra's algorithm for nonnegative weights.
There are at most extractions and at most successful decreases. The indexed priority queue maintains each vertex's current array position and updates this index table on every swap, so locating a key for DecreaseKey costs . Preallocate capacity . Repeated insertion costs , or bottom-up heap construction initializes the queue in time. Scanning adjacency lists costs in total.
For and , the heap-operation contributions are therefore
and the overall bound is
A uniform bound including larger arity and tiny graphs is . Arity greater than the number of vertices offers no useful extra heap levels. These bounds assume adjacency lists; with an adjacency matrix, scanning neighbours contributes instead. No rebuilding of the heap is required after each decrease.
With an adjacency list, initialization and the outer loop cost . Each vertex is visited once, and the adjacency scans inspect each edge of a graph twice, once from each endpoint. The total worst-case time is therefore , with labels and recursion-stack space. An adjacency matrix representation instead incurs scanning time.
Simple graph 2026-10-14
An undirected simple graph is exactly a pair of sets
Thus every edge is a two-element set of distinct vertices. The unordered pair equals , so there is no direction. The distinctness condition excludes self-loops, and using a set of edges excludes parallel copies. A simple graph may have vertices with no incident edges; does not by itself determine . For example, and have the same edge set but different vertex sets.[ref]
In the six-vertex example, the vertex neighbourhood of is , so its degree of a vertex is . In label order , the degree sequence is
This is the handshaking lemma: count each edge once at each of its two endpoints. The average degree of a graph here is . The degree sequence is a compact consistency check on an edge list; an odd sum could not describe any finite undirected graph. It also forces the number of odd degrees of vertices to be even, since the even terms do not affect the parity of the sum.
The adjacency matrix in the figure uses label order . Its entry is one exactly when , and zero otherwise. It is a symmetric matrix with zero diagonal, and each row sum gives the corresponding vertex degree. For example, row is . The fourteen ones count both directions of the seven undirected edges; they do not indicate fourteen different edges. This translates a picture into a representation suitable for calculation.
The restrictions matter. A directed graph uses an ordered pair to distinguish from , so reachability can depend on direction. A multigraph can contain several distinct edges between the same vertices; adding another would raise and to four without adding a new neighbour. A self-loop at contributes two to its undirected vertex degree, making it four, because both endpoints lie at . Specify whether self-loops are allowed in a multigraph. Finally, a weighted graph attaches numerical information to edges: if links carry travel times, minimizing the number of edges need not minimize total time. These are changes to the model, rather than changes to how the same simple graph is drawn.
Sparse graph Created 2026-10-14 Updated 2026-10-25
A family of graphs is sparse when its edge count grows substantially more slowly than the square of its vertex count; a common convention is that , where and count vertices and edges. State the intended asymptotic convention explicitly. An adjacency list then uses fewer storage entries than an adjacency matrix.
Spectral graph theory 2026-10-14
Spectral graph theory studies graphs through eigenvalues and eigenvectors of associated matrices, including the adjacency matrix and Laplacian matrix. A graph eigenvalue usually refers to the adjacency-matrix spectrum unless another matrix is specified.
For a directed graph with adjacency matrix , let record whether a path visits precisely the vertices of once and ends at . The singleton states are true. A larger state is true exactly when some predecessor has a true state for and an edge to . Removing or adjoining the last edge proves this recurrence by mathematical induction on . There are states, each requiring at most predecessor checks, giving time and storage. A true state for certifies a Hamiltonian path.
A finite nonempty Directed acyclic graph has a unique topological sort exactly when it has a Hamiltonian path. A Hamiltonian path forces the relative order of every consecutive pair and therefore of all vertices. Conversely, in a unique topological sort, every consecutive pair must have a forward edge: if such an edge were absent, swapping that adjacent pair would preserve all edge constraints and produce a second topological sort. The consecutive edges give a Hamiltonian path. Consequently one may compute any topological sort and test its consecutive edges, taking time on an adjacency matrix representation.