Use adjacency lists and a FIFO queue to implement the deletion rule in time complexity . Compute each initial degree of a vertex once, mark every vertex alive, and put all vertices of degree of a vertex zero or one in the FIFO queue. Each vertex is inserted at most once. Repeatedly remove the front vertex , mark it dead, and traverse its original adjacency list. For each still-alive graph neighbour , decrease the stored degree of a vertex of by one; if it has just become one, append . A vertex already queued can drop from one to zero before its turn, but it stays queued and requires no second insertion. Stop when the FIFO queue is empty; the alive vertices induce .
For the displayed example, initially enqueue in that order. The successive FIFO queues, after each deletion and all its updates, are
This explains the delayed deletion of : its initial degree of a vertex was three, but the relevant degree of a vertex is always its current one in the surviving induced subgraph. Removing only the original vertices of degree of a vertex one would give the wrong answer.
Initialization inspects every vertex and every adjacency list entry once. During deletion each original adjacency list is traversed at most once, so at most entries are inspected in an undirected graph. All insertions, removals and stored-degree updates cost constant time each. Thus total time complexity is and additional storage, beyond the adjacency lists, is . The cost includes isolated vertices; repeatedly rescanning the whole surviving graph after each deletion would lose this bound. The single-threshold FIFO queue method is enough for the 2-core; the full k-core of a graph decomposition computes all thresholds.
Matching (graph theory) Created 2026-10-14 Updated 2026-10-20
A matching in a graph is a set of edges of an undirected graph with no shared endpoints: each vertex has capacity for at most one selected edge. It describes simultaneous compatible pairs, such as jobs assigned to distinct available workers, or tasks each occupying two resources that cannot be shared. The empty set is a valid matching in a graph.[ref]
For a finite simple graph , write when is selected and otherwise. The vertex capacity constraint is exactly
These are constraints on a discrete selection, not a requirement that every vertex be used. A matching in a graph with matching saturation of all vertices is a perfect matching; an unmatched vertex in a matching uses none of its capacity.
The objective must be specified separately. A maximum cardinality matching selects as many edges as possible; a maximum-weight matching selects the greatest total benefit; a minimum-weight perfect matching minimizes cost while requiring every vertex to be paired. A maximal matching only says that no additional edge fits alongside the current choices. The four-vertex path graph below separates these notions: choosing the middle edge blocks both outer edges, yet replacing it by those two edges pairs more vertices.
This model is useful because conflicts are local at vertices, while the quality of a selection can depend on coordinated changes along a whole augmenting path in a matching. A greedy matching gives a quick feasible selection; Berge's theorem explains when searching for such changes has reached a maximum cardinality matching. Repeating the pairing problem over time leads instead to proper edge colouring, where each time slot is a matching in a graph.
Among all acyclic graphs contained in a finite weighted undirected graph, with no requirement to connect vertices, one optimum is obtained by keeping only strictly negative edges and computing their minimum spanning forest. Removing a nonnegative edge never worsens weight or creates a cycle. Within a connected component of the negative-edge subgraph, any disconnected candidate forest can be extended by a negative crossing edge, strictly improving its weight. Hence an optimum must span each such component and minimise its tree weight. Kruskal's algorithm on the negative edges therefore solves the problem. Zero-weight edges are optional when they preserve acyclicity.
Multiple edges 2026-10-14
Multiple edges are distinct edges with the same pair of endpoint vertices in an undirected graph. A multigraph permits them; a simple graph does not. In an orientation of a graph of a multigraph, each such edge receives its own direction, so two of them can supply opposite directed edges between the same vertices.
Neighbour enumeration 2026-10-14
Neighbour enumeration reports the neighbours of a specified vertex. For a simple graph, scan its adjacency list and report each entry. With constant-time list access and work per entry, a list of length needs time in Big O notation, conventionally written for nonempty lists. Use vertex degree for an undirected graph and outdegree for a directed graph. Obtaining the list reference can take constant time; consuming it requires visiting every entry.[ref]
In our undirected example, enumerating 's neighbours reads : three entries. Scanning row of the full adjacency matrix reads six entries, , to produce the same answer. In the directed variant, enumerating 's outgoing neighbours reads no neighbour entries, but still needs constant work to locate and recognize its empty list. For a multigraph, scanning lists enumerates incident edges with multiplicity; reporting only distinct neighbours additionally requires removing repetitions.
For a short time complexity argument, each reported entry requires at least one output operation, and one scan suffices. Across all vertices, the undirected entry count is by the handshaking lemma; the directed count is . A graph search that processes each vertex once and scans each of its entries once therefore does structural work, provided its visited-state access and FIFO queue or stack operations also have the required constant-time costs. With a full adjacency matrix, scanning every row instead inspects entries. This is how the representation enters the analysis of breadth-first search and depth-first search.
An induced subgraph game is a transferable utility game represented by a weighted undirected graph with one vertex per player; a coalition's value is the sum of the edge weights in its induced subgraph. With no self-loops,
where each unordered pair is counted once and an absent edge has weight zero. Weights may have either sign. In an induced subgraph game with self-loops, write the loop weight at as and add , counting each loop once. In particular, when loops are allowed and is zero otherwise.[ref]
A decision problem is in NP if every yes-instance has a complexity certificate of length bounded by a polynomial in the input length, and a deterministic verifier can check that certificate in polynomial time. More precisely, for some polynomial and verifier ,
where runs in polynomial time. Equivalently, a nondeterministic machine decides the problem in polynomial time. A problem is NP-complete if it belongs to NP and is NP-hard: every problem in NP has a polynomial-time many-one reduction to it. Such a reduction maps instances to instances with if and only if is a yes-instance of the target problem.
For 3-SAT, the complexity certificate is one truth value for each Boolean variable. Check every Boolean literal, negate its variable's truth value when appropriate, evaluate the disjunction in each Boolean clause, and check their conjunction. This takes time linear in the encoded Boolean formula, apart from equally polynomial bookkeeping for variable names. A satisfying assignment passes; an unsatisfiable Boolean formula has no passing assignment. Thus 3-SAT belongs to NP.
For the diagram's three-colour clause gadget, name the three colours by the graph triangle . Each input is adjacent to , so each has colour or . Suppose that none has colour . Then all three have colour . Because is adjacent to and to , neither has colour . The edge forces these two colours to be and in some order. The graph triangle now forces to have colour . Since is adjacent to and , it must have colour . The graph triangle forces to have colour . But is adjacent to , which also has colour , contradicting a proper graph colouring. Therefore at least one input has colour .
To give the polynomial-time many-one reduction, use one common palette graph triangle . For each Boolean variable , create two graph vertices and join them to each other and to . This Boolean-pair colouring gadget forces them to have opposite colours . For each Boolean clause, introduce five fresh auxiliary graph vertices and the edges of the three-colour clause gadget, identifying its inputs with that clause's three Boolean literal vertices and using the common . In the notation of the diagram, its ten additional edges are the two triangles and , the bridge , and the three input edges. With variables and clauses the constructed undirected graph has vertices and at most edges. Repeated literals do not affect the argument. Its construction takes polynomial time.
A proper graph colouring defines a consistent truth assignment by declaring true precisely when its vertex has colour . The only-if result just proved makes every clause true. Conversely, a satisfying assignment colours every literal vertex consistently, and the supplied if-direction extends each satisfied clause's colours to its fresh auxiliary vertices. These extensions do not conflict, since different clauses share only already-coloured palette and literal vertices. Thus the Boolean formula is satisfiable exactly when the constructed undirected graph is three-colourable. Since 3-SAT is NP-complete, composition of reductions proves NP-hardness of the three-colourability problem.
Finally, a list of three colour labels, one for each graph vertex, is a complexity certificate for the three-colourability problem. Checking all edges takes time. Hence this problem is in NP as well, and the three-colourability problem is NP-complete.
Choose the oriented incidence matrix convention with at an edge's tail and at its head. Let be net supply, so . The uncapacitated minimum-cost flow problem on a finite directed graph is
or . Negative denotes net demand. Costs may have either sign; the problem can be infeasible or unbounded.
For vertex network dual potentials , the optimization Lagrangian is
The infimum over is finite exactly when every network reduced cost is nonnegative. Thus the Lagrangian dual problem and complementary slackness are
A feasible flow and feasible network dual potentials satisfying these equalities have equal costs and are optimal by weak duality.
If the underlying undirected graph is connected, deleting one redundant balance row makes the oriented incidence matrix have rank . A set of independent edge columns is exactly a spanning tree. Set all non-tree flows to zero, solve the tree balances, and check nonnegativity to obtain a basic feasible solution. Basic tree edges may have zero flow, which is degeneracy in linear programming. Requiring on tree edges determines network dual potentials up to a common additive constant. If every non-tree network reduced cost is nonnegative, the tree flow is optimal. This is the basis of the network simplex algorithm. If the graph is disconnected, solve the balances separately in each component; each component must have total net supply zero and uses its own spanning tree.
Run breadth-first search separately in every component of the undirected graph. Give a starting vertex colour zero and each newly discovered neighbour the opposite colour. Reject if an edge joins two vertices with the same assigned colour; otherwise accept after all components have been explored.
If the algorithm accepts, its assignments constitute a graph colouring with two colours. If it rejects, the two search-tree paths and the conflicting edge contain an odd cycle, on which alternating two colours cannot close consistently. Equivalently, a valid graph colouring with two colours fixes the parity of every path from a component's root, so the detected conflict is impossible in a two-colourable graph. The breadth-first search work is with adjacency lists. Therefore
This is also the two-colourability criterion for bipartite graphs.
In bond percolation on an undirected graph , a configuration is . The edge is open when and closed when . Under , the coordinates are independent and identically distributed random variables with the Bernoulli distribution of parameter . For a countable edge set, use the product sigma-algebra and the product measure
The open edges form a random subgraph with the original graph vertices. Its connected components of a graph are the percolation clusters. Write when an open graph path joins to ; a zero-length graph path is allowed, so always holds. The randomness is in the independently open bonds; all vertices remain present.
The global Markov property for a directed acyclic graph requires, for all pairwise disjoint vertex sets , that D-separation of and by in implies . Two Markov equivalent directed acyclic graphs encode exactly the same such D-separations. The structural characterization is that they have the same skeleton of a directed graph and the same unshielded colliders. A distribution has faithfulness of a directed acyclic graph when its conditional independences are exactly those encoded by D-separation; this includes the global Markov implication as well as its converse.
The population PC algorithm uses an exact conditional independence oracle. Start with the complete undirected graph, and conditioning-set size . At each size, examine ordered adjacent pairs . Test subsets of size until independence is found or all such subsets have been examined. On finding it, delete and record a symmetric separating set . Ordered pairs ensure that subsets from either endpoint's neighbours are considered. Increase until no adjacent ordered pair has enough remaining neighbours to supply a set of that size. Rechecking eligibility after deletion, or freezing the neighbours at each level and then deleting, gives the same population skeleton under the hypothesis below.
Next, for each unshielded triple with nonadjacent, orient precisely when . Propagate directions that are forced without introducing a directed cycle or an additional unshielded collider. In particular, with nonadjacent forces ; an undirected edge with a directed path from to forces ; and with nonadjacent forces . The first avoids a new unshielded collider, the second a directed cycle. For the third, would force and to avoid cycles, creating the prohibited unshielded collider .
For a fully specified exact completion, list all acyclic orientations of the recovered skeleton which extend the collider arrows and have exactly the recorded unshielded colliders. Direct an edge if and only if all listed graphs orient it the same way; otherwise leave it undirected. This finite enumeration implements the definition of the completed partially directed acyclic graph; orientation propagation is the usual efficient way to obtain the same completion. The equivalence-class proof below uses the exact completion description and does not need an unproved completeness claim about a chosen subset of propagation rules.
To prove correctness, assume faithfulness of a directed acyclic graph to . A true edge cannot be D-separated by any set excluding its endpoints: its length-one path is always active. Thus a true edge is never deleted. Conversely, take nonadjacent and choose their order so that is earlier than in a topological ordering of . Then is a nondescendant and nonparent of . Its parent set gives D-separation of and . To see this local graphical fact, a path beginning is blocked by the conditioned parent , a noncollider. A path beginning with an arrow out of must encounter a first collider before reaching the nondescendant . That collider is a descendant of , and neither it nor any of its descendants can be a parent of in an acyclic graph. Hence conditioning on does not open it.
All parent edges survive. If has not already been deleted, remains among 's neighbours excluding . It is therefore tested by size , and faithfulness forces deletion. The size loop cannot stop prematurely while this set remains eligible. This proves exact recovery of the skeleton of a directed graph.
For an unshielded triple , if it is a noncollider in , its length-two path remains active unless is conditioned on. Thus every separator of contains . If it is a collider, conditioning on opens the length-two path, so no separator can contain . Faithfulness turns these graphical statements into the recorded separator test. Therefore the collider phase recovers precisely all unshielded colliders. By the skeleton and collider characterization of Markov equivalence, the acyclic extensions with exactly these colliders are exactly the Markov equivalence of directed acyclic graphs class of . In particular that set is nonempty, and the completion returns its CPDAG. This proves population PC correctness under faithfulness.
For the four-variable example, the only removable pairs are , with separator , and , with separator . The remaining skeleton has edges . The unshielded triples and both have center outside the separator of , so both are unshielded colliders. Every remaining edge is thereby oriented:
The other two unshielded triples are noncolliders, consistent with the separator of . There is no undirected edge left, so the equivalence class consists of this unique Directed acyclic graph. This identification is about the given faithful observational distribution; general PC algorithm outputs need not identify a unique causal direction.
Explicit reference to laws is not necessary for every good scientific explanation. Laws remain indispensable in many explanations, but their occurrence alone is not sufficient either. The issue turns partly on whether a law means a contingent regularity of nature, any supporting generalization, or even a mathematical necessity.
The deductive-nomological model offers a strong positive case. Laws and circumstances entail the phenomenon, and at least one law is essential to the derivation. For example, Newton's second law and an inverse-square gravitational force, with appropriate initial conditions, yield predictions for an idealized two-body orbit. A universal relation unifies cases that otherwise look like unrelated observations. Carl Hempel and Paul Oppenheim explicitly develop adequacy conditions for such deductive explanations; their 1948 paper should not be read as a finished treatment of every statistical explanation.[ref]
However, derivability does not always give the right explanatory direction. In a simplified geometrical optics model, a vertical pole of height on level ground casts a shadow of length at solar elevation . Given and , one derives ; given and , one derives . The same geometrical relations enter both derivations. Yet the shadow does not normally explain why the pole was built to that height. The reverse calculation is a way to measure its height. The difference concerns which features produce or constrain which others, rather than deductive validity alone.
Mechanistic explanation is another challenge to a compulsory law-based format. A clock stopped because debris blocked a particular wheel, thereby preventing the mechanism from advancing. Inspecting the obstruction, removing it and observing restored operation can answer the causal question with considerable precision. The explanation describes organization and a relevant difference-making event without stating a universal law. It is more informative about this failure than the observation that every component obeyed Newtonian mechanics.
A defender of the covering-law model can reply that the causal account relies implicitly on regularities: debris that offers no resistance would not stop the wheel. This is a fair warning against treating a bare chronology as an explanation. But it does not establish that explanatory understanding requires identifying exceptionless fundamental laws, or that replacing the account with a complete microscopic derivation would improve the answer. Stable, tested relations in the actual operating regime may be sufficient.
An explanation can also turn on a mathematical constraint. Suppose an engineer asks why a connected network with four odd-degree junctions cannot be inspected by a route using every segment exactly once. Represent junctions as vertices and segments as edges of an undirected graph. Every intermediate visit pairs an incoming and an outgoing edge, so only the two endpoints of an open trail can have odd vertex degree. Four such vertices therefore exclude an Eulerian trail. The impossibility persists if segment lengths, construction materials or walking speeds change while the connections remain fixed. This is the obstruction in the Seven Bridges of Königsberg.[ref]
The physical application requires that the graph represent the allowed routes correctly. Once that is granted, the explanatory necessity comes from parity, rather than a contingent physical law. Calling every mathematical constraint a law would preserve the original claim only by greatly widening its meaning. A critic may restrict “scientific” to causal explanations, but that restriction needs justification when applied mathematics answers a concrete engineering question.
Thus laws are powerful explanatory resources, and good explanations normally support relevant what-if judgements. Those judgements can be grounded in laws, mechanisms or mathematical constraints. Requiring explicit reference to laws imposes an unnecessarily narrow format; requiring some disciplined account of dependence is much more defensible.
Initialize and elsewhere. Perform full passes over the directed edges, applying edge relaxation whenever is finite. For an undirected graph, process each edge in both directions. Stop early if a pass makes no change.
Each finite label records the cost of a discovered directed walk, so it never understates the true infimum. After passes, relaxation has propagated along every route of at most edges, so the label is no greater than the cost of any such route. If no reachable negative-cost closed walk exists, an optimal route can be chosen without repeated vertices and has at most edges. These inequalities prove that the final labels are the desired shortest path lengths.
An additional pass checks for an improving edge from a reachable vertex. If one exists, report a reachable negative-cost cycle: finite shortest distances cannot be assigned to vertices reachable from that cycle. Mark those vertices by forward reachability if individual answers are wanted. In particular, a reachable negative undirected edge becomes a negative two-arc closed walk under the bidirected interpretation; generic signed weights do not guarantee finite answers.
Each pass costs , giving for the usual Bellman-Ford algorithm bound. Including initialization gives , which also handles an edgeless graph honestly; these coincide in order when .
All edge lengths are positive, so run the Dijkstra algorithm from every source , retaining distances and a shortest-path tree of its reachable component. Each run takes with a binary heap. The following scans after each run use only additional work.
For a directed graph, inspect every closing edge and consider when is reachable. The tree route from to followed by this edge is a closed walk. Every directed cycle supplies one such upper bound by choosing any of its vertices as ; the shortest route to its predecessor is no longer than the corresponding cycle segment. Positivity lets any repeated portion be removed, so the smallest candidate is the shortest directed-cycle length.
For an undirected graph, do not combine an edge with the distance between its endpoints indiscriminately: that can count traversal of one bridge out and back as a false cycle. Instead inspect only edges absent from the current shortest-path tree, with both endpoints reachable, and consider
The two tree routes and this non-tree edge contain a genuine cycle. If they share a prefix, its cost is counted twice, so that cycle is no longer than the candidate. Every candidate is consequently at least the global shortest-cycle length.
To prove equality is attained, take a shortest cycle and a source on it. If either cycle edge incident to is absent from the tree, its candidate uses a shortest route no longer than the rest of , so it is at most the length of . Otherwise both incident edges are in the tree, and their other endpoints lie in different branches below . Along the remaining segment of , some edge crosses between different branches. Such an edge is not a tree edge. The two distances to its endpoints are bounded by the two corresponding, disjoint segments of from ; their sum plus the crossing edge is at most the length of . Thus some candidate is no greater than the optimum, completing the proof.
Return the smallest finite candidate, or report acyclicity if none exists. The total running time is , as required. The ordinary convention is a simple graph; if parallel edges are allowed, track actual edge identities when excluding tree edges, and treat a self-loop as its own cycle rather than discarding it. This is shortest cycle by repeated shortest-path trees.
First run breadth-first search, ignoring weights, to obtain the minimum number of edges from the source to each reachable vertex. Then compute weighted distances only along edges that advance one breadth-first layer:
d[source] = 0; all other d[v] = infinity
for u in nondecreasing BFS-layer order:
    for each outgoing edge (u,v):
        if h[v] == h[u]+1:
            if d[u]+w(u,v) < d[v]:
                d[v] = d[u]+w(u,v)
                predecessor[v] = u
Unreachable vertices keep distance . For an undirected graph, scan both orientations of each edge.
To justify discarding other routes, a shortest path can be taken simple because every weight is positive. A simple path of edges has weight in
Every path with at least edges weighs at least . Consequently every minimum-weight path must also have the minimum possible number of edges: this is minimum-hop dominance for nearly unit weights.
A minimum-hop path to uses exactly edges. Every prefix of such a path must itself have minimum hop count, since replacing a longer prefix by a shorter one would shorten the whole route. Hence it advances from layer to layer at every step. The retained edges form a Directed acyclic graph, ordered by . The displayed dynamic programming recurrence therefore finds the cheapest of all minimum-hop paths, which by the preceding bound is a true shortest path.
Figure 1.
Disjoint weight bands for simple paths with different hop counts
. Details.
With an adjacency list, both the breadth-first search and the layer-ordered relaxations take time and total storage, where . The queue order from breadth-first search already supplies the layer order; no sorting or priority queue is needed. This improves the usual binary-heap Dijkstra bound and is linear in the input size.
Proper edge coloring 2026-10-14
A proper edge colouring gives different labels to any two distinct edges sharing a vertex. We work with finite undirected graphs without self-loops; distinct parallel edges in a multigraph must also have different colours. For a simple graph, whose edges are two-element sets, the condition is
Every colour class is a matching in a graph. Conversely, a set partition of the edges into matchings in a graph supplies a proper edge colouring. Thus minimizing colours means grouping all the edges into as few matchings in a graph as possible.
The line graph makes the relationship with proper vertex colouring explicit: replace each original edge by a vertex, joining two new vertices exactly when their original edges share an endpoint. A proper edge colouring of becomes a proper vertex colouring of its line graph , so . For a multigraph, retain a distinct new vertex for each parallel edge.[ref]
Pseudoforest 2026-10-14
A pseudoforest is an undirected graph in which every connected component of a graph contains at most one cycle in a graph. Thus each component is a tree or a unicyclic component. A finite tree component has one fewer edge than vertices; a finite unicyclic component has equally many edges and vertices.
In a positive-weight directed graph, run the Dijkstra algorithm from each source and minimize over closing edges. In an undirected graph, minimize only over edges absent from the current shortest-path tree. A tree edge would otherwise give a spurious traversal out and back. A non-tree candidate contains a genuine cycle no longer than its score, even when the two tree routes share a prefix.
For the undirected optimum, choose a shortest cycle and a source on it. If an incident cycle edge is absent from the tree, its candidate is bounded by the cycle length. Otherwise its two neighbours lie in distinct tree branches, and some edge on the remaining cycle segment crosses branches. That edge is non-tree; shortest distances to its endpoints are bounded by the two complementary cycle segments, again giving a candidate no greater than the optimum. Thus the minimum candidate equals the shortest-cycle length. Repeated Dijkstra algorithm runs take running time with a binary heap.
Shortest path problem 2026-10-14
The shortest path problem asks for a graph path from a source vertex to a destination vertex minimizing its total edge weight. Here is the cost of traversing edge , and costs add along the graph path. If no route exists, its shortest-path distance is . With nonnegative edge weights, deleting cycles in a graph from a walk never increases its cost, so repetitions cannot improve the optimum.
Consider the undirected graph with vertex set and the six edge weights
Each edge can be traversed in either direction at the same cost. The direct graph path costs ; costs ; costs . The cheapest graph path is , costing . The remaining graph path costs , exhausting the possibilities without repeated vertices.
Figure 1.
The shortest path problem: three highlighted edges cost less than the direct connection
. Details.
Thus fewest edges and least total cost are different objectives. Breadth-first search minimizes the number of edges, which suffices when every edge has the same positive cost. Unequal nonnegative costs call for the Dijkstra algorithm. On a map, weights might be minutes rather than kilometres: a longer-looking route can arrive sooner. This is why a weighted graph separates the network's connections from what a particular journey costs.
Suppose two pieces occupy a common connected component of a graph in an unweighted undirected graph. For integers , in each round an evader moves at most edges, then a pursuer moves up to edges along a shortest path to the new evader position, stopping upon capture. Let be their finite graph distance at a surviving round boundary.
The triangle inequality bounds the separation after the evader moves by . If that separation is at most , the pursuer captures it. Otherwise the pursuer reduces it by exactly , giving
Hence every surviving history has at most rounds. With a finite branching factor, the surviving search tree is finite and depth-first tree search becomes a complete search algorithm. This does not make its first goal optimal for arbitrary rewards. Initial reachability is essential: an infinite graph distance supplies no decreasing finite bound.