struct::graph::op(n)
โจ NAME โจ
okay bestie, this is the struct::graph::op(n) manual โ yes, the Tcl Data Structures one, and it's lowkey iconic. The name is:
struct::graph::op - Operation for (un)directed graph objects
๐ฆ SYNOPSIS ๐ฆ
here's the vibe check for what you can call, fr fr:
package require Tcl 8.6 9
package require struct::graph::op ?0.11.4?
struct::graph::op::toAdjacencyMatrix g
struct::graph::op::toAdjacencyList G ?options...?
struct::graph::op::kruskal g
struct::graph::op::prim g
struct::graph::op::isBipartite? g ?bipartvar?
struct::graph::op::tarjan g
struct::graph::op::connectedComponents g
struct::graph::op::connectedComponentOf g n
struct::graph::op::isConnected? g
struct::graph::op::isCutVertex? g n
struct::graph::op::isBridge? g a
struct::graph::op::isEulerian? g ?tourvar?
struct::graph::op::isSemiEulerian? g ?pathvar?
struct::graph::op::dijkstra g start ?options...?
struct::graph::op::distance g origin destination ?options...?
struct::graph::op::eccentricity g n ?options...?
struct::graph::op::radius g ?options...?
struct::graph::op::diameter g ?options...?
struct::graph::op::BellmanFord G startnode
struct::graph::op::Johnsons G ?options...?
struct::graph::op::FloydWarshall G
struct::graph::op::MetricTravellingSalesman G
struct::graph::op::Christofides G
struct::graph::op::GreedyMaxMatching G
struct::graph::op::MaxCut G U V
struct::graph::op::UnweightedKCenter G k
struct::graph::op::WeightedKCenter G nodeWeights W
struct::graph::op::GreedyMaxIndependentSet G
struct::graph::op::GreedyWeightedMaxIndependentSet G nodeWeights
struct::graph::op::VerticesCover G
struct::graph::op::EdmondsKarp G s t
struct::graph::op::BusackerGowen G desiredFlow s t
struct::graph::op::ShortestsPathsByBFS G s outputFormat
struct::graph::op::BFS G s ?outputFormat...?
struct::graph::op::MinimumDiameterSpanningTree G
struct::graph::op::MinimumDegreeSpanningTree G
struct::graph::op::MaximumFlowByDinic G s t blockingFlowAlg
struct::graph::op::BlockingFlowByDinic G s t
struct::graph::op::BlockingFlowByMKM G s t
struct::graph::op::createResidualGraph G f
struct::graph::op::createAugmentingNetwork G f path
struct::graph::op::createLevelGraph Gf s
struct::graph::op::TSPLocalSearching G C
struct::graph::op::TSPLocalSearching3Approx G C
struct::graph::op::createSquaredGraph G
struct::graph::op::createCompleteGraph G originalEdges
๐ DESCRIPTION ๐
okay so the package described by this document, struct::graph::op, is a companion to the package struct::graph. It provides a series of common operations and algorithms applicable to (un)directed graphs.
Despite being a companion the package is not directly dependent on struct::graph, only on the API defined by that package. I.e. the operations of this package can be applied to any and all graph objects which provide the same API as the objects created through struct::graph.
๐ฅ OPERATIONS ๐ฅ
struct::graph::op::toAdjacencyMatrix g
This command takes the graph g and returns a nested list containing the adjacency matrix of g.
The elements of the outer list are the rows of the matrix, the inner elements are the column values in each row. The matrix has "n+1" rows and columns, with the first row and column (index 0) containing the name of the node the row/column is for. All other elements are boolean values, True if there is an arc between the 2 nodes of the respective row and column, and False otherwise.
note bestie: the matrix is symmetric. It does not represent the directionality of arcs, only their presence between nodes. It is also unable to represent parallel arcs in g.
struct::graph::op::toAdjacencyList G ?options...?
Procedure creates for input graph G, its representation as Adjacency List. It handles both directed and undirected graphs (default is undirected). It returns dictionary that for each node (key) returns list of nodes adjacent to it. When considering weighted version, for each adjacent node there is also weight of the edge included.
Arguments:
- Graph object
G(input) โ A graph to convert into an Adjacency List.
Options:
-directedโ By defaultGis operated as if it were an Undirected graph. Using this option tells the command to handleGas the directed graph it is.-weightsโ By default any weight information the graphGmay have is ignored. Using this option tells the command to put weight information into the result. In that case it is expected that all arcs have a proper weight, and an error is thrown if that is not the case.
struct::graph::op::kruskal g
This command takes the graph g and returns a list containing the names of the arcs in g which span up a minimum weight spanning tree (MST), or, in the case of an un-connected graph, a minimum weight spanning forest (except for the 1-vertex components). Kruskal's algorithm is used to compute the tree or forest. This algorithm has a time complexity of O(E*log E) or O(E* log V), where V is the number of vertices and E is the number of edges in graph g.
The command will throw an error if one or more arcs in g have no weight associated with them.
A note regarding the result, the command refrains from explicitly listing the nodes of the MST as this information is implicitly provided in the arcs already.
struct::graph::op::prim g
This command takes the graph g and returns a list containing the names of the arcs in g which span up a minimum weight spanning tree (MST), or, in the case of an un-connected graph, a minimum weight spanning forest (except for the 1-vertex components). Prim's algorithm is used to compute the tree or forest. This algorithm has a time complexity between O(E+V*log V) and O(V*V), depending on the implementation (Fibonacci heap + Adjacency list versus Adjacency Matrix). As usual V is the number of vertices and E the number of edges in graph g.
The command will throw an error if one or more arcs in g have no weight associated with them.
A note regarding the result, the command refrains from explicitly listing the nodes of the MST as this information is implicitly provided in the arcs already.
struct::graph::op::isBipartite? g ?bipartvar?
This command takes the graph g and returns a boolean value indicating whether it is bipartite (true) or not (false). If the variable bipartvar is specified the two partitions of the graph are there as a list, if, and only if the graph is bipartit. If it is not the variable, if specified, is not touched.
struct::graph::op::tarjan g
This command computes the set of strongly connected components (SCCs) of the graph g. The result of the command is a list of sets, each of which contains the nodes for one of the SCCs of g. The union of all SCCs covers the whole graph, and no two SCCs intersect with each other.
The graph g is acyclic if all SCCs in the result contain only a single node. The graph g is strongly connected if the result contains only a single SCC containing all nodes of g.
struct::graph::op::connectedComponents g
This command computes the set of connected components (CCs) of the graph g. The result of the command is a list of sets, each of which contains the nodes for one of the CCs of g. The union of all CCs covers the whole graph, and no two CCs intersect with each other.
The graph g is connected if the result contains only a single SCC containing all nodes of g.
struct::graph::op::connectedComponentOf g n
This command computes the connected component (CC) of the graph g containing the node n. The result of the command is a set which contains the nodes for the CC of n in g.
The command will throw an error if n is not a node of the graph g.
struct::graph::op::isConnected? g
This is a convenience command determining whether the graph g is connected or not. The result is a boolean value, true if the graph is connected, and false otherwise.
struct::graph::op::isCutVertex? g n
This command determines whether the node n in the graph g is a cut vertex (aka articulation point). The result is a boolean value, true if the node is a cut vertex, and false otherwise.
The command will throw an error if n is not a node of the graph g.
struct::graph::op::isBridge? g a
This command determines whether the arc a in the graph g is a bridge (aka cut edge, or isthmus). The result is a boolean value, true if the arc is a bridge, and false otherwise.
The command will throw an error if a is not an arc of the graph g.
struct::graph::op::isEulerian? g ?tourvar?
This command determines whether the graph g is eulerian or not. The result is a boolean value, true if the graph is eulerian, and false otherwise.
If the graph is eulerian and tourvar is specified then an euler tour is computed as well and stored in the named variable. The tour is represented by the list of arcs traversed, in the order of traversal.
struct::graph::op::isSemiEulerian? g ?pathvar?
This command determines whether the graph g is semi-eulerian or not. The result is a boolean value, true if the graph is semi-eulerian, and false otherwise.
If the graph is semi-eulerian and pathvar is specified then an euler path is computed as well and stored in the named variable. The path is represented by the list of arcs traversed, in the order of traversal.
struct::graph::op::dijkstra g start ?options...?
This command determines distances in the weighted g from the node start to all other nodes in the graph. The options specify how to traverse graphs, and the format of the result.
Two options are recognized
-arcmode modeโ the modes you're allowed to pass aredirectedandundirected. With directed traversal every single arc gets walked from source to target, no detours. With undirected traversal all the arcs get traversed the opposite way too, so it's giving both directions at once. And the default?undirected, bestie. ๐ฆ-outputformat formatโ accepted values aredistancesandtree. Either way you get back a dictionary keyed by the names of every node in the graph, so nothing's left out. Withdistancesthe value is the distance of the node tostart. Withtreethe value is the path from the node tostartโ not counting the node itself, but yes countingstart. Andtreeis the default, iykyk. ๐
๐ struct::graph::op::distance g origin destination ?options...?
This one figures out the (un)directed distance between the two nodes origin and destination in the graph g. It accepts the -arcmode option of struct::graph::op::dijkstra, that's the whole vibe. โจ
๐ struct::graph::op::eccentricity g n ?options...?
Determines the (un)directed eccentricity of the node n in the graph g. It accepts the -arcmode option of struct::graph::op::dijkstra.
And like, what even is eccentricity? It's the maximal (un)directed distance between the node and any other node in the graph. The most dramatic distance it has with anyone. ๐
๐ struct::graph::op::radius g ?options...?
Gets you the (un)directed radius of the graph g. It accepts the -arcmode option of struct::graph::op::dijkstra.
The (un)directed radius of a graph is the minimal (un)directed eccentricity out of all the nodes in the graph. The chillest one.
๐ struct::graph::op::diameter g ?options...?
Gets you the (un)directed diameter of the graph g. It accepts the -arcmode option of struct::graph::op::dijkstra.
The (un)directed diameter of a graph is the maximal (un)directed eccentricity out of all the nodes in the graph. The most extra one, periodt.
๐ struct::graph::op::BellmanFord G startnode
It's out here searching for the shortest paths between the chosen node and all the other nodes in graph G. Built on the relaxation method, no cap. And compared to struct::graph::op::dijkstra? It doesn't need the assumption that every weight on the edges in the input graph G has to be positive. Iconic.
That generality tho โ it sets the complexity of the algorithm to O(V*E), where V is the number of vertices and E is the number of edges in graph G. ๐
Arguments:
- Graph object
G(input) โ directed, connected and edge weighted graphG, with no negative cycles in it. (Presence of cycles with the negative sum of weight means there is no shortest path, since the total weight becomes lower each time the cycle is traversed.) Negative weights on edges are allowed though. ๐ซถ - Node
startnode(input) โ the node for which we find all shortest paths to each other node in graphG.
Result:
- Dictionary containing, for each node (the key), distances to each other node in graph
G.
Note: if the algorithm finds a negative cycle, it will return an error message. Not me getting caught in a negative cycle ๐ญ
๐ struct::graph::op::Johnsons G ?options...?
Searching for shortest paths between all pairs of vertices in a graph. For sparse graphs it's asymptotically quicker than the struct::graph::op::FloydWarshall algorithm. Johnson's algorithm uses struct::graph::op::BellmanFord and struct::graph::op::dijkstra as subprocedures, so it's basically running a little squad. ๐
Time complexity: O(n**2*log(n) +n*m), where n is the number of nodes and m is the number of edges in graph G.
Arguments:
- Graph object
G(input) โ directed graphG, weighted on edges and not containing any cycles with negative sum of weights (the presence of such cycles means there is no shortest path, since the total weight becomes lower each time the cycle is traversed). Negative weights on edges are allowed. ๐ธ
Options:
-filterโ returns only existing distances, cuts allInfvalues for non-existing connections between pairs of nodes. So it filters out the fake ones, slay.
Result:
- Dictionary containing distances between all pairs of vertices.
๐ struct::graph::op::FloydWarshall G
Searching for shortest paths between all pairs of edges in weighted graphs. โจ
Time complexity: O(V^3) โ where V is number of vertices.
Memory complexity: O(V^2).
Arguments:
- Graph object
G(input) โ directed and weighted graphG.
Result:
- Dictionary containing shortest distances to each node from each node.
Note: the algorithm finds solutions dynamically. It compares all possible paths through the graph between each pair of vertices. The graph shouldn't possess any cycle with negative sum of weights (the presence of such cycles means there is no shortest path, since the total weight becomes lower each time the cycle is traversed).
But plot twist, bestie โ on the other hand the algorithm can be used to find those cycles! If any shortest distance found by the algorithm for any nodes v and u (when v is the same node as u) is negative, then that node surely belongs to at least one negative cycle. Detective energy. ๐ต๏ธโ๏ธ
๐ struct::graph::op::MetricTravellingSalesman G
An algorithm for solving a metric variation of the Travelling salesman problem. TSP is NP-Complete, so there is no efficient algorithm to solve it โ not a skill issue, it's just math. Greedy methods are getting extremely slow as the set of nodes grows. ๐ญ
Arguments:
- Graph object
G(input) โ undirected, weighted graphG.
Result:
- Approximated solution of minimum Hamilton Cycle โ a closed path visiting all nodes, each exactly one time.
Note: it's a 2-approximation algorithm.
๐ struct::graph::op::Christofides G
Another algorithm for solving the metric TSP problem. The Christofides implementation uses Max Matching for reaching a better approximation factor. Glow up. ๐
Arguments:
- Graph Object
G(input) โ undirected, weighted graphG.
Result:
- Approximated solution of minimum Hamilton Cycle โ a closed path visiting all nodes, each exactly one time.
Note: it's is a 3/2 approximation algorithm.
๐ struct::graph::op::GreedyMaxMatching G
A Greedy Max Matching procedure, which finds the maximal matching (not the maximum one, okay, read carefully bestie) for a given graph G. It adds edges to the solution, beginning from the edges with the lowest cost. Budget-friendly behaviour. ๐ธ
Arguments:
- Graph Object
G(input) โ undirected graphG.
Result:
- Set of edges โ the max matching for graph
G.
๐ struct::graph::op::MaxCut G U V
An algorithm solving a Maximum Cut Problem.
Arguments:
- Graph Object
G(input) โ the graph to cut. โ๏ธ - List
U(output) โ variable storing the first set of nodes (cut) given by the solution. - List
V(output) โ variable storing the second set of nodes (cut) given by the solution.
Result:
- The algorithm returns the number of edges between the found two sets of nodes.
Note: MaxCut is a 2-approximation algorithm.
๐ struct::graph::op::UnweightedKCenter G k
An approximation algorithm that solves a k-center problem.
Arguments:
- Graph Object
G(input) โ undirected complete graphG, which satisfies the triangle inequality. - Integer
k(input) โ positive integer that sets the number of nodes that will be included in the k-center.
Result:
- Set of nodes โ k center for graph
G.
Note: UnweightedKCenter is a 2-approximation algorithm.
๐ struct::graph::op::WeightedKCenter G nodeWeights W
An approximation algorithm that solves a weighted version of the k-center problem.
Arguments:
- Graph Object
G(input) โ undirected complete graphG, which satisfies the triangle inequality. - Integer
W(input) โ positive integer that sets the maximum possible weight of the k-center found by the algorithm. - List
nodeWeights(input) โ list of nodes and its weights in graphG.
Result:
- Set of nodes, which is the solution found by the algorithm.
Note: WeightedKCenter is a 3-approximation algorithm.
๐ struct::graph::op::GreedyMaxIndependentSet G
A maximal independent set is an independent set such that adding any other node to the set forces the set to contain an edge. It's giving "you can't sit with us" but for vertices. ๐
Algorithm for input graph G returns a set of nodes (list), which are contained in the Max Independent Set found by the algorithm.
๐ struct::graph::op::GreedyWeightedMaxIndependentSet G nodeWeights
Weighted variation of the Maximal Independent Set. It takes as an input argument not only graph G but also a set of weights for all vertices in graph G.
Note: read also the Maximal Independent Set description for more info.
๐ struct::graph::op::VerticesCover G
A vertices cover is a set of vertices such that each edge of the graph is incident to at least one vertex of the set. This 2-approximation algorithm searches for the minimum vertices cover, which is a classical optimization problem in computer science and is a typical example of an NP-hard optimization problem that has an approximation algorithm. For input graph G the algorithm returns the set of edges (list), which is the Vertex Cover found by the algorithm. ๐
๐ struct::graph::op::EdmondsKarp G s t
An improved Ford-Fulkerson's algorithm, computing the maximum flow in a given flow network G. Big main character energy. ๐ฅ
Arguments:
Graph Object G(input) โ Weighted and directed graph. Each edge should have a set integer attribute that we treat as the maximum throughputs that can be carried by that link (edge). ๐ฆNode s(input) โ the node that is a source for graph G. โจNode t(input) โ the node that is a sink for graph G. ๐
Result: The procedure returns the dictionary containing throughputs for all edges. For each key (the edge between nodes u and v in the form of list u v) there is a value that is a throughput for that key. Edges where throughput values are equal to 0 are not returned (it is like there was no link in the flow network between nodes connected by such edge). ๐
The general idea of algorithm is finding the shortest augumenting paths in graph G, as long as they exist, and for each path updating the edge's weights along that path, with maximum possible throughput. The final (maximum) flow is found when there is no other augumenting path from source to sink. ๐ฅ
Note: Algorithm complexity: O(V*E), where V is the number of nodes and E is the number of edges in graph G. ๐ง
struct::graph::op::BusackerGowen G desiredFlow s t
okay so this one finds a solution for a minimum cost flow problem. The goal is to find a flow, whose max value can be desiredFlow, from source node s to sink node t in given flow network G. That network, except throughputs at edges, has also defined a non-negative cost on each edge โ cost of using that edge when directing flow with that edge (it can illustrate e.g. fuel usage, time or any other measure dependent on usages). ๐๐จ
Arguments
Graph Object G(input) โ Flow network (directed graph), each edge in graph should have two integer attributes:costandthroughput. ๐Integer desiredFlow(input) โ Max value of the flow for that network. ๐ขNode s(input) โ The source node for graphG. ๐Node t(input) โ The sink node for graphG. ๐
Result
Dictionary containing values of used throughputs for each edge (key) found by algorithm. ๐
Note: Algorithm complexity: O(V**2*desiredFlow), where V is the number of nodes in graph G. โณ
struct::graph::op::ShortestsPathsByBFS G s outputFormat
Shortest pathfinding algorithm using BFS method. In comparison to struct::graph::op::dijkstra it can work with negative weights on edges. Of course negative cycles are not allowed. Algorithm is better than dijkstra for sparse graphs, but also there exist some pathological cases (those cases generally don't appear in practise) that make time complexity increase exponentially with the growth of the number of nodes. ๐ญ
Arguments
Graph Object G(input) โ Input graph. ๐ธNode s(input) โ Source node for which all distances to each other node in graphGare computed. ๐
Options and result
distancesโ When selectedoutputFormatisdistances, procedure returns dictionary containing distances between source nodesand each other node in graphG. ๐pathsโ When selectedoutputFormatispaths, procedure returns dictionary containing for each nodev, a list of nodes, which is a path between source nodesand nodev. ๐ค๏ธ
struct::graph::op::BFS G s ?outputFormat...?
Breadth-First Search โ algorithm creates the BFS Tree. Memory and time complexity: O(V + E), where V is the number of nodes and E is number of edges. ๐ณ
Arguments
Graph Object G(input) โ Input graph. ๐ฆNode s(input) โ Source node for BFS procedure. โจ
Options and result
graphโ When selectedoutputFormatisgraph, procedure returns a graph structure (struct::graph), which is equivalent to BFS tree found by algorithm. ๐treeโ When selectedoutputFormatistree, procedure returns a tree structure (struct::tree), which is equivalent to BFS tree found by algorithm. ๐ฒ
struct::graph::op::MinimumDiameterSpanningTree G
The goal is to find for input graph G, the spanning tree that has the minimum diameter value. ๐ฏ
General idea of algorithm is to run BFS over all vertices in graph G. If the diameter d of the tree is odd, then we are sure that tree given by BFS is minimum (considering diameter value). When, diameter d is even, then optimal tree can have minimum diameter equal to d or d-1. ๐ค
In that case, what algorithm does is rebuilding the tree given by BFS, by adding a vertice between root node and root's child node (nodes), such that subtree created with child node as root node is the greatest one (has the greatests height). In the next step for such rebuilded tree, we run again BFS with new node as root node. If the height of the tree didn't changed, we have found a better solution. ๐
For input graph G algorithm returns the graph structure (struct::graph) that is a spanning tree with minimum diameter found by algorithm. ๐
struct::graph::op::MinimumDegreeSpanningTree G
Algorithm finds for input graph G, a spanning tree T with the minimum possible degree. That problem is NP-hard, so algorithm is an approximation algorithm. ๐
Let V be the set of nodes for graph G and let W be any subset of V. Lets assume also that OPT is optimal solution and ALG is solution found by algorithm for input graph G. ๐
It can be proven that solution found with the algorithm must fulfil inequality:
((|W| + k - 1) / |W|) <= ALG <= 2*OPT + log2(n) + 1.
Arguments
Graph Object G(input) โ Undirected simple graph. ๐ซถ
Result
Algorithm returns graph structure, which is equivalent to spanning tree T found by algorithm. ๐ณ
struct::graph::op::MaximumFlowByDinic G s t blockingFlowAlg
Algorithm finds maximum flow for the flow network represented by graph G. It is based on the blocking-flow finding methods, which give us different complexities what makes a better fit for different graphs. ๐ฅ
Arguments
Graph Object G(input) โ Directed graphGrepresenting the flow network. Each edge should have attributethroughputset with integer value. ๐งNode s(input) โ The source node for the flow networkG. ๐Node t(input) โ The sink node for the flow networkG. ๐
Options
dinicโ Procedure will find maximum flow for flow networkGusing Dinic's algorithm (struct::graph::op::BlockingFlowByDinic) for blocking flow computation. ๐งฎmkmโ Procedure will find maximum flow for flow networkGusing Malhotra, Kumar and Maheshwari's algorithm (struct::graph::op::BlockingFlowByMKM) for blocking flow computation. ๐
Result
Algorithm returns dictionary containing it's flow value for each edge (key) in network G. ๐
Note:struct::graph::op::BlockingFlowByDinicgivesO(m*n^2)complexity andstruct::graph::op::BlockingFlowByMKMgivesO(n^3)complexity, wherenis the number of nodes andmis the number of edges in flow networkG. โฑ๏ธ
struct::graph::op::BlockingFlowByDinic G s t
Algorithm for given network G with source s and sink t, finds a blocking flow, which can be used to obtain a maximum flow for that network G. ๐ฐ
Arguments
Graph Object G(input) โ Directed graphGrepresenting the flow network. Each edge should have attributethroughputset with integer value. ๐งNode s(input) โ The source node for the flow networkG. ๐Node t(input) โ The sink node for the flow networkG. ๐
Result
Algorithm returns dictionary containing it's blocking flow value for each edge (key) in network G. ๐ฆ
Note: Algorithm's complexity isO(n*m), wherenis the number of nodes andmis the number of edges in flow networkG. โณ
struct::graph::op::BlockingFlowByMKM G s t
Algorithm for given network G with source s and sink t, finds a blocking flow, which can be used to obtain a maximum flow for that network G. ๐ฐ
Arguments
Graph Object G(input) โ Directed graphGrepresenting the flow network. Each edge should have attributethroughputset with integer value. ๐งNode s(input) โ The source node for the flow networkG. ๐Node t(input) โ The sink node for the flow networkG. ๐
Result
Algorithm returns dictionary containing it's blocking flow value for each edge (key) in network G. ๐ฆ
Note: Algorithm's complexity isO(n^2), wherenis the number of nodes in flow networkG. โณ
struct::graph::op::createResidualGraph G f
Procedure creates a residual graph (or residual network ) for network G and given flow f. โป๏ธ
Arguments
Graph Object G(input) โ Flow network (directed graph where each edge has set attribute:throughput). ๐งdictionary f(input) โ Current flows in flow networkG. ๐ฅ
Result
Procedure returns graph structure that is a residual graph created from input flow network G. ๐
๐ struct::graph::op::createAugmentingNetwork โ G f path
Okay bestie, this one literally builds you an augmenting network ๐. You hand it a residual network G, a flow f, and an augmenting path path, and it cooks up the augmenting network for you. It's giving network-flow glow-up energy โจ.
Arguments:
- Graph Object
G(input) โ the residual network, which is a directed graph, and every single edge on it has two attributes set:throughputandcost. Two. Attributes. No cap. ๐ซถ - Dictionary
f(input) โ a dictionary holding, for every edge (that's the key ๐), the current value of the flow running along that edge. - List
path(input) โ the augmenting path: a set of edges, given as a list, that we're creating the network modification for.
Result: the algorithm hands you back a graph structure containing the modified augmenting network. Slay ๐ฆ.
๐ struct::graph::op::createLevelGraph โ Gf s
For a given residual graph Gf, this procedure finds the level graph. Lowkey one of the prettiest little helpers in here ๐
.
Arguments:
- Graph Object
Gf(input) โ a residual network where each edge has its attributethroughputset to some certain value. - Node
s(input) โ the source node for the residual networkGf๐.
Result: the procedure returns a level graph created from the input residual network. Chef's kiss โจ.
๐ฅ struct::graph::op::TSPLocalSearching โ G C
Okay so this is a heuristic of local searching for the Travelling Salesman Problem ๐๐จ. You give it some solution to TSP and it checks whether it's possible to find a better one. And because TSP is, and I quote, a well known NP-Complete problem ๐, this is an approximation algorithm โ with a 2 approximation factor. Not me reminding you that perfection was never on the table ๐.
Arguments:
- Graph Object
G(input) โ an undirected and complete graph with the attribute"weight"set on each single edge. - List
C(input) โ a list of edges forming a Hamiltonian cycle, which is the solution of the TSP Problem for graphG.
Result: the algorithm returns the best solution for the TSP problem that it was able to find ๐.
Note: the solution totally depends on which beginning cycle C you picked ๐. It is not true that a better cycle assures a better solution will be found โ but practise shows you should give a starting cycle with as small a sum of weights as possible. So like, do your best on the input, bestie.
๐ struct::graph::op::TSPLocalSearching3Approx โ G C
Same vibe, different factor โจ. This is also a heuristic of local searching for the Travelling Salesman Problem: for some solution of TSP, it checks if a better solution can be found. And since TSP is a well known NP-Complete problem ๐ญ, it's an approximation algorithm โ this time with a 3 approximation factor.
Arguments:
- Graph Object
G(input) โ an undirected and complete graph with attributes"weight"set on each single edge. - List
C(input) โ a list of edges being a Hamiltonian cycle, the solution of the TSP Problem for graphG.
Result: it returns the best solution for the TSP problem that it was able to find ๐.
Note: in practise the 3-approximation algorithm turns out to be far more effective than the 2-approximation โ but it gives a worser approximation factor ๐. And further heuristics of local searching (e.g. 4-approximation) don't give enough boost to square the increase of approximation factor, so 2 and 3 approximations are the ones mainly used. The way that tradeoff worksโฆ iconic but rude ๐.
๐ฆ struct::graph::op::createSquaredGraph โ G
So an X-Squared graph is a graph with the same set of nodes as the input graph G, but a different set of edges ๐ธ. The X-Squared graph has edge (u,v) if and only if the distance between the u and v nodes is not greater than X and u != v. Periodt ๐
.
For input graph G, the procedure returns its two-squared graph.
Note: the distances used when choosing the new set of edges are considering the number of edges, not the sum of weights at edges. Important distinction, don't get it twisted ๐.
โญ struct::graph::op::createCompleteGraph โ G originalEdges
For input graph G, this procedure adds the missing arcs to make it a complete graph ๐. And it also holds in the variable originalEdges the set of arcs that graph G possessed before that operation โ so it's keeping receipts of the before-picture ๐ธโจ.
๐ง BACKGROUND THEORY AND TERMS
Okay bestie, this is the lore section ๐. Grab a snack, we're doing theory ๐.
๐ SHORTEST PATH PROBLEM
Definition (single-pair shortest path problem):
Formally, given a weighted graph (let V be the set of vertices, and E a set of edges), and one vertice v of V, find a path P from v to a v' of V so that the sum of weights on edges along the path is minimal among all paths connecting v to v' โจ.
Generalizations:
- The single-source shortest path problem, in which we have to find shortest paths from a source vertex
vto all other vertices in the graph. - The single-destination shortest path problem, in which we have to find shortest paths from all vertices in the graph to a single destination vertex
v. This can be reduced to the single-source shortest path problem by reversing the edges in the graph ๐. - The all-pairs shortest path problem, in which we have to find shortest paths between every pair of vertices
v,v'in the graph.
Note: the result of the Shortest Path problem can be a Shortest Path tree โ a subgraph of a given (possibly weighted) graph, constructed so that the distance between a selected root node and all other nodes is minimal. It's a tree because if there are two paths between the root node and some vertex v (i.e. a cycle), we can delete the last edge of the longer path without increasing the distance from the root node to any node in the subgraph ๐ณ. No cap, it's just that clean.
๐ TRAVELLING SALESMAN PROBLEM
Definition:
For a given edge-weighted graph (weights on edges should be positive), the goal is to find the cycle that visits each node in the graph exactly once โ a Hamiltonian cycle ๐.
Generalizations:
- Metric TSP โ a very natural restriction of the TSP is to require that the distances between cities form a metric, i.e., they satisfy the triangle inequality ๐. That is, for any 3 cities
A,BandC, the distance betweenAandCmust be at most the distance fromAtoBplus the distance fromBtoC. Most natural instances of TSP satisfy this constraint. - Euclidean TSP โ Euclidean TSP, or planar TSP, is the TSP with the distance being the ordinary Euclidean distance. Euclidean TSP is a particular case of TSP with triangle inequality, since distances in the plane obey the triangle inequality ๐ธ. However, it seems to be easier than general TSP with triangle inequality. For example, the minimum spanning tree of the graph associated with an instance of Euclidean TSP is a Euclidean minimum spanning tree, and so can be computed in expected
O(n log n)time fornpoints (considerably less than the number of edges). This enables the simple 2-approximation algorithm for TSP with triangle inequality above to operate more quickly โก. - Asymmetric TSP โ in most cases, the distance between two nodes in the TSP network is the same in both directions. The case where the distance from
AtoBis not equal to the distance fromBtoAis called asymmetric TSP ๐. A practical application of an asymmetric TSP is route optimisation using street-level routing (asymmetric due to one-way streets, slip-roads and motorways) ๐ฃ๏ธ.
๐ซถ MATCHING PROBLEM
Definition:
Given a graph G = (V,E), a matching or edge-independent set M in G is a set of pairwise non-adjacent edges โ that is, no two edges share a common vertex ๐. A vertex is matched if it is incident to an edge in the matching M. Otherwise the vertex is unmatched.
Generalizations:
- Maximal matching โ a matching
Mof a graphGwith the property that if any edge not inMis added toM, it is no longer a matching. That is,Mis maximal if it is not a proper subset of any other matching in graphG. In other words, a matchingMof a graphGis maximal if every edge inGhas a non-empty intersection with at least one edge inMโจ. - Maximum matching โ a matching that contains the largest possible number of edges. There may be many maximum matchings ๐. The matching number of a graph
Gis the size of a maximum matching. Note that every maximum matching is maximal, but not every maximal matching is a maximum matching. Read that one twice, bestie ๐ . - Perfect matching โ a matching which matches all vertices of the graph. That is, every vertex of the graph is incident to exactly one edge of the matching ๐. Every perfect matching is maximum and hence maximal. In some literature, the term complete matching is used. A perfect matching is also a minimum-size edge cover. Moreover, the size of a maximum matching is no larger than the size of a minimum edge cover ๐ฆ.
- Near-perfect matching โ a matching in which exactly one vertex is unmatched ๐. This can only occur when the graph has an odd number of vertices, and such a matching must be maximum. If, for every vertex in a graph, there is a near-perfect matching that omits only that vertex, the graph is also called factor-critical โญ.
Related terms:
- Alternating path โ given a matching
M, an alternating path is a path in which the edges belong alternatively to the matching and not to the matching ๐. - Augmenting path โ given a matching
M, an augmenting path is an alternating path that starts from and ends on free (unmatched) vertices ๐.
๐ CUT PROBLEMS ๐
Definition:
okay so a cut is literally a partition of the vertices of a graph into two disjoint subsets. The cut-set of the cut is the set of edges whose end points are in different subsets of the partition. Edges are said to be crossing the cut if theyโre in its cut-set. ๐
Formally:
- a cut
C = (S,T)is a partition ofVof a graphG = (V, E). - an
s-tcutC = (S,T)of a flow networkN = (V, E)is a cut ofNsuch thatsis included inSandtis included inT, wheresandtare the source and the sink ofNrespectively. - The cut-set of a cut
C = (S,T)is such set of edges from graphG = (V, E)that each edge(u, v)satisfies condition thatuis included inSandvis included inT.
In an unweighted undirected graph, the size or weight of a cut is the number of edges crossing the cut. In a weighted graph, the same term is defined by the sum of the weights of the edges crossing the cut. โจ
In a flow network, an s-t cut is a cut that requires the source and the sink to be in different subsets, and its cut-set only consists of edges going from the source's side to the sink's side. The capacity of an s-t cut is defined by the sum of capacity of each edge in the cut-set. ๐ง
The cut of a graph can sometimes refer to its cut-set instead of the partition. iykyk
Generalizations:
- Minimum cut - A cut is minimum if the size of the cut is not larger than the size of any other cut. ๐
- Maximum cut - A cut is maximum if the size of the cut is not smaller than the size of any other cut. ๐ฅ
- Sparsest cut - The Sparsest cut problem is to bipartition the vertices so as to minimize the ratio of the number of edges across the cut divided by the number of vertices in the smaller half of the partition. ๐ฆ
๐ฏ K-CENTER PROBLEM ๐ฏ
Definitions:
- Unweighted K-Center โ For any set
S( which is subset ofV) and nodev, let theconnect(v,S)be the cost of cheapest edge connectingvwith any node inS. The goal is to find suchS, that|S| = kandmax_v{connect(v,S)}is possibly small. ๐
In other words, we can use it i.e. for finding best locations in the city ( nodes of input graph ) for placing k buildings, such that those buildings will be as close as possible to all other locations in town. ๐๏ธ
- Weighted K-Center โ The variation of unweighted k-center problem. Besides the fact graph is edge-weighted, there are also weights on vertices of input graph
G. We've got also restrictionW. The goal is to choose such set of nodesS( which is a subset ofV), that it's total weight is not greater thanWand also function:max_v { min_u { cost(u,v) }}has the smallest possible worth (vis a node inVanduis a node inS). โ๏ธ
๐ FLOW PROBLEMS ๐
Definitions:
- the maximum flow problem โ the goal is to find a feasible flow through a single-source, single-sink flow network that is maximum. The maximum flow problem can be seen as a special case of more complex network flow problems, such as the circulation problem. The maximum value of an
s-tflow is equal to the minimum capacity of ans-tcut in the network, as stated in the max-flow min-cut theorem. ๐
More formally for flow network G = (V,E), where for each edge (u, v) we have its throuhgput c(u,v) defined. As flow F we define set of non-negative integer attributes f(u,v) assigned to edges, satisfying such conditions:
[1]โ for each edge(u, v)inGsuch condition should be satisfied:0 <= f(u,v) <= c(u,v)[2]โ NetworkGhas source nodessuch that the flowFis equal to the sum of outcoming flow decreased by the sum of incoming flow from that source nodes.[3]โ NetworkGhas sink nodetsuch that the-Fvalue is equal to the sum of the incoming flow decreased by the sum of outcoming flow from that sink nodet.[4]โ For each node that is not a source or sink the sum of incoming flow and sum of outcoming flow should be equal.
- the minimum cost flow problem โ the goal is finding the cheapest possible way of sending a certain amount of flow through a flow network. ๐ฐ
- blocking flow โ a blocking flow for a residual network
Gfwe name such flowbinGfthat:[1]โ Each path from sink to source is the shortest path inGf.[2]โ Each shortest path inGfcontains an edge with fully used throughput inGf+b.
- residual network โ for a flow network
Gand flowfresidual network is built with those edges, which can send larger flow. It contains only those edges, which can send flow larger than0. ๐ - level network โ it has the same set of nodes as residual graph, but has only those edges
(u,v)fromGffor which such equality is satisfied:distance(s,u)+1 = distance(s,v). ๐ถ - augmenting network โ it is a modification of residual network considering the new flow values. Structure stays unchanged but values of throughputs and costs at edges are different. โจ
๐งฎ APPROXIMATION ALGORITHM ๐งฎ
k-approximation algorithm:
Algorithm is a k-approximation, when for ALG (solution returned by algorithm) and OPT (optimal solution), such inequality is true:
- for minimalization problems:
ALG/OPT <= k - for maximalization problems:
OPT/ALG <= k
periodt ๐
๐ REFERENCES ๐
[1]โ Adjacency matrix โ[http://en.wikipedia.org/wiki/Adjacency_matrix][2]โ Adjacency list โ[http://en.wikipedia.org/wiki/Adjacency_list][3]โ Kruskal's algorithm โ[http://en.wikipedia.org/wiki/Kruskal%27s_algorithm][4]โ Prim's algorithm โ[http://en.wikipedia.org/wiki/Prim%27s_algorithm][5]โ Bipartite graph โ[http://en.wikipedia.org/wiki/Bipartite_graph][6]โ Strongly connected components โ[http://en.wikipedia.org/wiki/Strongly_connected_components][7]โ Tarjan's strongly connected components algorithm โ[http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm][8]โ Cut vertex โ[http://en.wikipedia.org/wiki/Cut_vertex][9]โ Bridge โ[http://en.wikipedia.org/wiki/Bridge_(graph_theory)][10]โ Bellman-Ford's algorithm โ[http://en.wikipedia.org/wiki/Bellman-Ford_algorithm][11]โ Johnson's algorithm โ[http://en.wikipedia.org/wiki/Johnson_algorithm][12]โ Floyd-Warshall's algorithm โ[http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm][13]โ Travelling Salesman Problem โ[http://en.wikipedia.org/wiki/Travelling_salesman_problem][14]โ Christofides Algorithm โ[http://en.wikipedia.org/wiki/Christofides_algorithm][15]โ Max Cut โ[http://en.wikipedia.org/wiki/Maxcut][16]โ Matching โ[http://en.wikipedia.org/wiki/Matching][17]โ Max Independent Set โ[http://en.wikipedia.org/wiki/Maximal_independent_set][18]โ Vertex Cover โ[http://en.wikipedia.org/wiki/Vertex_cover_problem][19]โ Ford-Fulkerson's algorithm โ[http://en.wikipedia.org/wiki/Ford-Fulkerson_algorithm][20]โ Maximum Flow problem โ[http://en.wikipedia.org/wiki/Maximum_flow_problem][21]โ Busacker-Gowen's algorithm โ[http://en.wikipedia.org/wiki/Minimum_cost_flow_problem][22]โ Dinic's algorithm โ[http://en.wikipedia.org/wiki/Dinic's_algorithm][23]โ K-Center problem โ[http://www.csc.kth.se/~viggo/wwwcompendium/node128.html][24]โ BFS โ[http://en.wikipedia.org/wiki/Breadth-first_search][25]โ Minimum Degree Spanning Tree โ[http://en.wikipedia.org/wiki/Degree-constrained_spanning_tree][26]โ Approximation algorithm โ[http://en.wikipedia.org/wiki/Approximation_algorithm]
๐ BUGS, IDEAS, FEEDBACK ๐
This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category struct :: graph of the Tcllib Trackers [http://core.tcl.tk/tcllib/reportlist]. Please also report any ideas for enhancements you may have for either package and/or documentation.
When proposing code changes, please provide unified diffs, i.e the output of diff -u.
Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar.
๐ KEYWORDS ๐
adjacency list, adjacency matrix, adjacent, approximation algorithm, arc, articulation point, augmenting network, augmenting path, bfs, bipartite, blocking flow, bridge, complete graph, connected component, cut edge, cut vertex, degree, degree constrained spanning tree, diameter, dijkstra, distance, eccentricity, edge, flow network, graph, heuristic, independent set, isthmus, level graph, local searching, loop, matching, max cut, maximum flow, minimal spanning tree, minimum cost flow, minimum degree spanning tree, minimum diameter spanning tree, neighbour, node, radius, residual graph, shortest path, squared graph, strongly connected component, subgraph, travelling salesman, vertex, vertex cover
๐๏ธ CATEGORY ๐๏ธ
Data structures
ยฉ๏ธ COPYRIGHT ยฉ๏ธ
- Copyright (c) 2008 Alejandro Paz
<vidriloco@gmail.com> - Copyright (c) 2008 (docs) Andreas Kupries
<andreas_kupries@users.sourceforge.net> - Copyright (c) 2009 Michal Antoniewski
<antoniewski.m@gmail.com>
And thatโs the footer, bestie: source/version tcllib 0.11.4, page struct::graph::op(n). No date on this footer line, but thatโs the official stamp. ๐โจ
๐ฆ where this page comes from
- fedora 43: tcllib 2.0-3.fc43 ยท TCL
- fedora 44: tcllib 2.0-4.fc44 ยท TCL
- nixos 26.05: tcllib 2.0
- nixpkgs unstable: tcllib 2.0
- Copyright (c) 2008 Alejandro Paz <vidriloco@gmail\&.com>
- Copyright (c) 2008 (docs) Andreas Kupries <andreas_kupries@users\&.sourceforge\&.net>
- Copyright (c) 2009 Michal Antoniewski <antoniewski\&.m@gmail\&.com>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms