1function graph = randGraph(numVertices)
2% This function takes as input an integer number of vertices
3% and returns a MATLAB digraph
object representing a randomly
4% generated, strongly connected graph
7 error(
'randGraph:positiveVerticesRequired',
'Positive vertices required');
12 graph = addnode(graph, 1);
13 graph = addedge(graph, 1, 1);
17 % State variables needed
for the DFS-based strongConnect function
19 startTime = ones(1, numVertices) * -1;
20 lowestLink = startTime;
21 invStartTime = startTime;
23 tree = randSpanningTree(numVertices);
24 graph = strongConnect(tree, 1);
25 graph = reordernodes(graph, randperm(numVertices)); % To generate arbitrary permutations
27 % Nested function to avoid
using global state variables
28 function g = strongConnect(g, v)
29 startTime(v) = globalStartTime; % Order of observation in DFS sequence
30 invStartTime(startTime(v)) = v; % For inverse lookup when adding edges
31 lowestLink(v) = startTime(v); % Initially can only reach itself
32 globalStartTime = globalStartTime + 1;
34 [~, vertexIDs] = outedges(g, v);
35 for i = 1 : length(vertexIDs)
37 if startTime(w) == -1 % Vertex w has not been visited yet
38 g = strongConnect(g, w);
39 lowestLink(v) = min(lowestLink(v), lowestLink(w));
41 lowestLink(v) = min(lowestLink(v), startTime(w));
45 % If vertex v
is the root of a SCC but not the entire graph
's root
46 if lowestLink(v) == startTime(v) && startTime(v) > 1
47 descendantST = randi([startTime(v) globalStartTime - 1]);
48 ancestorST = randi([1 startTime(v) - 1]);
49 g = addedge(g, invStartTime(descendantST), invStartTime(ancestorST));
50 lowestLink(v) = ancestorST;
55% Generates a random spanning tree with the specified number of vertices
56function tree = randSpanningTree(numVertices)
58 tree = addnode(tree, numVertices);
60 % Note: This always joins vertex 1 to 2, we will relabel in randGraph
61 for i = 2 : numVertices
62 tree = addedge(tree, randi(i - 1), i);