Android uses a pattern to lock a smartphone. The common lock pattern is a 3×3 grid of 9 nodes. Sanghyun wants stronger security, so he is building an app that offers the lock patterns described here.
In his app a lock pattern has a size from 2×2 up to m×m, and only adjacent nodes can be connected. Two nodes are adjacent when one is directly next to the other horizontally, vertically, or diagonally. A node at one of the four corners is connected to 3 nodes, and every other node is connected to at most 8.
A lock pattern always has to form a spanning tree. A spanning tree is a set of edges of the graph that contains no closed loop. It also has to give a path between any two nodes, and it consists of m2=n vertices and n−1 edges. A single lock pattern admits many different spanning trees.
To count the spanning trees of a graph G, first number every vertex v1,…,vn. Then build the matrix T=[tij] this way.
The number of spanning trees is a cofactor of T.
cofactor of tij=(−1)i+jMij
Here Mij is the determinant of the (n−1)×(n−1) matrix obtained by deleting row i and column j from T. Every cofactor of T has the same value, whichever i and j you pick.
For example, the matrix T of the 2×2 pattern is as follows.
T=3−1−1−1−13−1−1−1−13−1−1−1−13
Taking i=1 and j=1, the cofactor comes out like this.
(−1)1+1M11=3−1−1−13−1−1−13=16
So the 2×2 pattern has 16 spanning trees.
The matrix T of the 3×3 pattern is as follows.
T=3−10−1−10000−15−1−1−1−10000−130−1−1000−1−105−10−1−10−1−1−1−18−1−1−1−10−1−10−150−1−1000−1−103−10000−1−1−1−15−10000−1−10−13
The cofactor of this matrix is the number of spanning trees of the 3×3 pattern.
Write a program that counts the spanning trees you can make on an m×m pattern.
The first line contains the number of test cases N (1≤N≤5). Each of the next N lines holds one test case, the pattern size m. (2≤m≤6)
For each test case, print on its own line the number of spanning trees you can make on the m×m pattern.
The m=2 pattern is a graph of 4 vertices that are all connected to each other, and it has 16 spanning trees.