Domain: Algorithms & Data Structures

Consider an n x m grid (2 <= n <= 12, 2 <= m <= 1000) where some cells are blocked. A Hamiltonian path visits every non-blocked cell exactly once. The task is to count Hamiltonian paths from cell (0,0) to cell (n-1, m-1), modulo 10^9+7. The grid is given as n lines of m characters where '.' is empty and '#' is blocked. If (0,0) or (n-1, m-1) is blocked, the answer is 0.

Describe a complete algorithm to solve this problem using broken profile dynamic programming (plug DP). Your answer must address ALL of the following points using the conventions specified below.

CONVENTIONS:
- The grid has n rows and m columns, 0-indexed.
- Cells are processed in column-major order (column 0 top-to-bottom, then column 1 top-to-bottom, etc.).
- The plug array is 0-indexed with exactly (n+1) entries.
- Component labels in the plug array are canonicalized by assigning integers 1, 2, 3, ... in left-to-right first-occurrence order.

ADDRESS EACH OF THE FOLLOWING:

1. PROFILE STRUCTURE: Define the broken profile as the boundary between processed and unprocessed cells. State the number of plug positions for an n-row grid. Describe the geometric shape of this boundary in terms of horizontal and vertical segments.

2. STATE BOUND: Using Catalan numbers, state the upper bound on the number of distinct canonical plug states for a profile with (n+1) positions. Give the exact numeric value for n = 12.

3. TRANSITION RULES FOR EMPTY CELLS: When processing an empty cell (i, j), define all valid transitions based on the values of the LEFT plug and TOP plug:
   (a) Both LEFT = 0 and TOP = 0
   (b) Exactly one of LEFT or TOP is nonzero
   (c) Both nonzero with different component labels
   (d) Both nonzero with the same component label
   For each case, state what outgoing plug values are produced and any validity constraints.

4. PREMATURE CYCLE REJECTION: Explain what happens in case (d) at a non-terminal cell and why the transition must be handled differently than case (c).

5. COMPONENT MERGING: When two components with different labels are merged in case (c), specify how the plug array is updated and how re-canonicalization is performed.

6. START CELL (0,0): State the valid outgoing plug configuration(s) for the path's starting endpoint. Specify which outgoing plugs may be nonzero and which must be zero, and justify using the degree constraint.

7. END CELL (n-1, m-1): State the required incoming plug configuration for valid Hamiltonian path termination. Specify conditions on LEFT, TOP, and all other plug positions.

8. SPACE MANAGEMENT: Describe how DP states are stored across cell transitions. State how many collections of states must be maintained simultaneously and the resulting space complexity in terms of Catalan numbers.

9. DP RECURRENCE: Write the DP update rule relating dp_next and dp_curr, specifying where canonicalization is applied.

10. TIME AND SPACE COMPLEXITY: State the overall time and space complexity in terms of n, m, and Catalan numbers. Justify feasibility for n = 12, m = 1000 by citing the numeric Catalan bound.

For verification: on a 3x3 grid with all cells empty, the number of Hamiltonian paths from (0,0) to (2,2) is exactly 2.

Grading rubric:
criterion: The response states that the broken profile has exactly n+1 plug positions for an n-row grid, and describes the profile as consisting of n horizontal segments and 1 vertical segment (or equivalently as a staircase or L-shaped boundary).
weight: 10
criterion: The response states that the number of distinct canonical plug states is bounded by the Catalan number C_{n+1}, and provides the exact numeric value C_13 = 742900 as the upper bound when n = 12.
weight: 10
criterion: The response defines canonicalization as assigning component labels 1, 2, 3, ... in left-to-right first-occurrence order across the plug array, ensuring a unique representation for each distinct connectivity pattern.
weight: 10
criterion: The response correctly states that when both LEFT and TOP plugs carry the same component label at a non-terminal cell, the transition must be rejected because it would create a premature cycle, which violates the Hamiltonian path property.
weight: 15
criterion: The response specifies that when merging two components with different labels, all occurrences of one label are replaced with the other throughout the plug array, followed by re-canonicalization of the entire state.
weight: 10
criterion: The response states that at the start cell (0,0), exactly one outgoing plug is set to a nonzero component label and the other must remain 0, because a path endpoint has degree 1.
weight: 10
criterion: The response states that at the end cell (n-1, m-1), exactly one of the two incoming plugs (LEFT or TOP) must be nonzero while the other is 0, AND all remaining plug positions in the array must be exactly 0.
weight: 15
criterion: The response provides the DP recurrence as dp_next[canonicalize(new_state)] += dp_curr[old_state] for each valid transition, or an equivalent formulation that explicitly applies canonicalization to the new state before accumulation.
weight: 5
criterion: The response states that exactly two DP state collections (current and next) are maintained at any time, and that this achieves space complexity of O(C_{n+1}) rather than storing states for all cells.
weight: 5
criterion: The response states the time complexity as O(n * m * C_{n+1}) or an asymptotically equivalent expression, and confirms feasibility for n = 12 and m = 1000 by citing the numeric bound C_13 = 742900.
weight: 10

Answer:
1. PROFILE STRUCTURE:
The broken profile is the boundary between processed cells (above and to the left of the current cell in column-major order) and unprocessed cells (below and to the right). It forms a staircase or L-shaped boundary consisting of exactly n horizontal segments and 1 vertical segment. The profile has exactly n+1 plug positions for a grid with n rows.

2. STATE BOUND:
The number of distinct canonical plug states on (n+1) positions is bounded by the Catalan number C_{n+1}. The Catalan number C_k = (2k)! / ((k+1)! * k!). For n = 12, the profile has 13 positions, so the bound is C_13 = 742,900.

3. TRANSITION RULES FOR EMPTY CELLS:
When processing cell (i, j), let L = LEFT plug value and T = TOP plug value.

(a) L = 0 and T = 0:
For an interior cell (not start or end): the cell must have degree 2, so if no segment enters from LEFT or TOP, the only valid choice is to start a new open component at this cell. Create a new component label k and set both outgoing plugs to that label: RIGHT = k and DOWN = k. This means the current cell contributes two incident edges, one to the right and one downward, and those two dangling ends belong to the same component to be connected later.
For the start or end cell: degree is 1, so exactly one outgoing plug gets label k, the other stays 0 (see points 6 and 7).

(b) Exactly one of L, T is nonzero (say value = p, the other = 0):
The existing segment continues through this cell. Two sub-options for degree-2 cells:
  - Continue RIGHT: set RIGHT plug = p, DOWN plug = 0
  - Continue DOWN: set DOWN plug = p, RIGHT plug = 0
For an endpoint cell (degree 1): the segment terminates. Set both outgoing plugs to 0.

(c) Both L and T nonzero with different labels (L = p, T = q, p != q):
The cell merges two distinct path segments. Both outgoing plugs become 0 (the cell consumes both incoming segments). The two components must be unified: replace all occurrences of max(p, q) with min(p, q) throughout the plug array, then re-canonicalize (see point 5).

(d) Both L and T nonzero with the same label (L = T = p):
This would close a cycle, so it is invalid for a Hamiltonian path and must be rejected. See point 4.

4. PREMATURE CYCLE REJECTION:
At any non-terminal cell, if L and T have the same component label, connecting them would join two ends of the same partial component and immediately create a cycle before all cells are finished. That is a premature cycle, so the transition must be rejected.

The terminal cell is also rejected in case (d), but for the full endpoint condition: using both incoming plugs would give degree 2 at (n-1, m-1), whereas a Hamiltonian path ending there requires degree 1. So valid termination is only the one-incoming-plug case from point 7.

5. COMPONENT MERGING:
When merging labels p and q (assume p < q without loss of generality): scan the entire plug array of (n+1) entries and replace every occurrence of q with p. Then re-canonicalize: scan the array left-to-right and assign new labels 1, 2, 3, ... to each distinct nonzero value in order of first appearance. This ensures the resulting state is in canonical form for hash map lookup.

6. START CELL (0,0):
Cell (0,0) is a path endpoint and must have degree 1. Since it is at position (0,0), there is no LEFT plug and no TOP plug (both are 0 by boundary conditions). The cell must produce exactly one outgoing plug set to component label 1:
  - Option A: RIGHT plug = 1, DOWN plug = 0 (path starts going right)
  - Option B: RIGHT plug = 0, DOWN plug = 1 (path starts going down)
Setting both to 1 would give degree 2, violating the endpoint constraint.

7. END CELL (n-1, m-1):
Cell (n-1, m-1) is the other path endpoint with degree 1. For a valid Hamiltonian path termination:
  - Exactly one of LEFT or TOP must be nonzero (one incoming segment)
  - The other must be zero
  - All remaining (n-1) plug positions in the array must be exactly 0
This ensures that no dangling path segments exist elsewhere in the grid, meaning all free cells have been incorporated into a single path from (0,0) to (n-1, m-1).

8. SPACE MANAGEMENT:
Two hash maps (or dictionaries) are maintained: dp_curr (states for the current cell being processed) and dp_next (states being built for the next cell). For each cell, iterate over all entries in dp_curr, compute valid transitions, and accumulate into dp_next. After processing the cell, set dp_curr = dp_next and reset dp_next to empty. This alternation means only O(C_{n+1}) state entries are stored at any time, giving space complexity O(C_{n+1}).

9. DP RECURRENCE:
For each state old_state in dp_curr with value dp_curr[old_state]:
  For each valid transition at the current cell producing new_state:
    dp_next[canonicalize(new_state)] += dp_curr[old_state]  (mod 10^9 + 7)

Here canonicalize(new_state) relabels the component IDs in the plug array as 1, 2, 3, ... by left-to-right first occurrence, ensuring a unique key for each connectivity pattern.

10. TIME AND SPACE COMPLEXITY:
- Number of distinct DP states per cell: O(C_{n+1}), bounded by Catalan number C_{n+1}
- For n = 12: C_13 = 742,900 states
- Transitions per state per cell: O(1) amortized (constant number of cases, plus O(n) for re-canonicalization, but n <= 12 is treated as constant)
- Total cells processed: n * m
- Time complexity: O(n * m * C_{n+1})
- Space complexity: O(C_{n+1})
- Feasibility for n = 12, m = 1000: the state cap is C_13 = 742,900, so memory remains bounded by storing at most two such state collections at once. This Catalan bound is the key reason the method is viable for width 12; in practice the number of reachable states is typically well below the worst-case cap.

VERIFICATION:
For the 3x3 all-empty grid, the two Hamiltonian paths from (0,0) to (2,2) are:
  Path 1: (0,0) -> (0,1) -> (0,2) -> (1,2) -> (1,1) -> (1,0) -> (2,0) -> (2,1) -> (2,2)
  Path 2: (0,0) -> (1,0) -> (2,0) -> (2,1) -> (1,1) -> (0,1) -> (0,2) -> (1,2) -> (2,2)
Count = 2.