An acyclical grid is a mapping of an acyclical graph (that is, a tree) where each node has no more than four edges onto a toroidal rectangular grid such that each cell of the grid is occupied by a node. Here is an example of an acyclical grid:
┴─┐╵╵│└┘└╴╶┴┬
╴╷╵┌┐│╷┌┬┐╶┐├
╷│╷╵│├┘│╵└╴│╵
┘└┴┐│└┬┤┌─┬┴─
╷╶─┤│╷╵├┤╶┘╶┐
│╶┐└┤└┬┤╵╷╶─┤
┤╷└─┴┬┤└┐└┬┬┴
│├──┐│├╴├─┤├╴
┘└┐┌┴┤└┐├╴╵╵┌
┌┬┘╵┌┴┐╵└─┐╶┘
┤└─┐│╷│┌┬╴╵╷╶
Some browser fonts have trouble rendering this in a properly monospaced way. If the grid looks off, please copy-paste it into a text editor of your choice.
Notice that this grid is toroidal: the left and right, as well as the top and bottom are connected preserving the axis you are moving along. For example, if you move left in the third row you eventually end up on the right of the third row and vice versa.
This grid is composed of box-drawing characters which fall into four classes:
- The characters
╵
,╶
,╷
, and╴
denote leaves (nodes with one edge) - The characters
│
and─
denote nodes with two edges in a collinear arrangement - The characters
┴
,├
,┬
, and┤
denote nodes with three edges - The characters
└
,┌
,┐
, and┘
denote nodes with two edges in a perpendicular arrangement
The characteristic matrix of an acyclical grid is a matrix comprising for each cell in the acyclical grid the class of the node positioned there. For instance, the characteristic matrix of the aforementioned grid is this:
3241124441133
1114424232123
1211234214121
4434243342332
1123211331414
2144343311123
3142333444333
2322423131331
4444334431114
4341434142414
3424212431111
A net puzzle is an n × m matrix of integers in the range from 1 to 4 such that it is the characteristic matrix of exactly one acyclical grid.
If you want to gain an intuitive understanding about net puzzles, you can play net from Simon Tatham's puzzle collection. Make sure that “wrapping” and “ensure unique solution” are both checked and that “barrier probability” is set to 0.
The challenge
Write a function or program that given two integers n and m in the range from 3 to 1023 generates a net puzzle of dimension n × m. You may optionally receive a third integer p in the range from 1 to 1023.
If you implement the variant with two arguments (the non-deterministic variant), then your submission shall with great probability return a different puzzle each time it is called. If you implement the variant with three arguments (the deterministic variant), then the set of puzzles generated for all p for a given pair (n, m) shall contain at least four different puzzles for each pair (n, m).
There are no further restrictions with respect to input and output.
Scoring
This challenge is code golf. The solution with the least number of octets wins.