Proofs: Incidence matrix
These are the human proofs of Incidence matrix, at full length.
The incidence-matrix operations keep the column invariant and answer the graph queries full
This proof shows: correctness.
We use the pseudocode of the page. The graph has the vertices and the edges , where edge has the ends and (the tail and the head if the graph is directed). The invariant is:
(C) has exactly columns. In the directed case, column has , and 0 elsewhere, with . In the undirected case, column has where , that is, 1 at each of two distinct ends, or 2 at the vertex of a self-loop, and 0 elsewhere.
With , the matrix has empty rows, and (C) holds.
ADD-EDGE. Line L1 adds the column with zeros, and no other column changes. In the directed case, , and line L2 writes in row and in row , two different cells. In the undirected case, line L3 adds 1 to row and then 1 to row of the new column. If the column has 1 in both rows; if the cell gets . In both cases column meets (C) for the new edge with and , and the matrix has columns.
ENDS. By (C), the nonzero entries of column are in the rows of the ends of and nowhere else. Lines L5 and L6 visit each row once and record with multiplicity , so in the undirected case they record and , which is twice for a self-loop at . In the directed case the entry is in row and the entry in row , so line L7 returns the tail and the head.
INCIDENT. By (C), if and only if , so line L8 returns exactly the edges at , each once.
ADJACENT. In the directed case, there is an edge from to if and only if some column has and , which by (C) is and . Lines L9 to L11 test this for each column and return true at the first one, or false after all . In the undirected case with , an edge joins and if and only if some column has nonzero entries in both rows; with , a self-loop at exists if and only if some column has , because by (C) the entry 2 occurs only for a self-loop.
Degrees. In the undirected case, by (C), counts each edge at once for each of its ends equal to , which is with a self-loop counted twice. In the directed case each edge leaving adds and each edge entering adds , so the row sum is .
Cost. ADD-EDGE appends one cell to each of rows, amortized. ENDS reads cells, INCIDENT reads cells, and ADJACENT reads at most cells. The matrix has cells.