You are given a collection of jigsaw puzzle pieces. Each piece has four edges: top, right, bottom, and left. A helper function match(edgeA, edgeB) is provided; it returns true if two edges can be connected and false otherwise.
The puzzle is known to form one complete rectangular grid, but the number of rows and columns is not given. Pieces may need to be rotated. Implement a solve(pieces) function that returns a valid rectangular arrangement of all pieces, including each piece's orientation, such that every horizontally or vertically adjacent pair of edges matches according to match.
You may assume:
-
Every piece must be used exactly once.
-
A valid solution exists.
-
The puzzle has no missing pieces.
-
Border edges do not need to match anything outside the puzzle.
Discuss the algorithm, data structures, and time and space complexity.