2
\$\begingroup\$

The treewidth is a measure of the count of original graph vertices mapped onto any tree vertex in an optimal tree decomposition.

I wrote Mathematica code to calculate Treewidth based on the Python code provided in the CodeGolf question.

I am now looking for a review in terms of approach, clarity, performance, etc.

eliminationWidth[graph_] := Module[{maxNeighbors = 0, currentGraph = graph, vertices, i, neighbors, newEdges},
 vertices = Union[Flatten[graph]];
 Do[
 neighbors = Union[
 Cases[currentGraph, {a_, i} :> a] ~Join~ 
 Cases[currentGraph, {i, b_} :> b]
 ];
 maxNeighbors = Max[Length[neighbors], maxNeighbors];
 newEdges = Select[Tuples[neighbors, 2], #[[1]] < #[[2]] &];
 currentGraph = Select[currentGraph, FreeQ[#, i] &] ~Join~ newEdges;
 , {i, Sort[vertices]}];
 maxNeighbors
 ]
treewidth[graph_] := Module[{vertices, minWidth, permutations, newGraph},
 vertices = Union[Flatten[graph]];
 minWidth = Length[vertices];
 permutations = Permutations[vertices];
 Do[
 newGraph = graph /. Thread[vertices -> perm];
 minWidth = Min[eliminationWidth[newGraph], minWidth];
 , {perm, permutations}];
 minWidth
 ]
(* Test cases *)
testCases = {
 {{0, 1}, {0, 2}, {0, 3}, {2, 4}, {3, 5}},
 {{0, 1}, {0, 2}, {1, 2}, {1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 4}, {3, 4}, {4, 6}, {4, 7}, {5, 6}, {6, 7}}
};
expectedResults = {1, 2};
(* Run tests *)
Do[
 result = treewidth[testCases[[i]]];
 Print["Test case ", i, ": Expected ", expectedResults[[i]], ", Got ", result, 
 If[result == expectedResults[[i]], " ✓", " ✗"]];
 , {i, Length[testCases]}]
Toby Speight
87.9k14 gold badges104 silver badges325 bronze badges
asked Jul 2 at 13:14
\$\endgroup\$

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.