#P4558. Sum of Visited Cells before Obstacle in Wrapped Grid Hamiltonian Cycle
Sum of Visited Cells before Obstacle in Wrapped Grid Hamiltonian Cycle
Sum of Visited Cells before Obstacle in Wrapped Grid Hamiltonian Cycle
Consider an (n \times m) grid with cells labeled from ((1,1)) to ((n,m)). A robot is launched each night from cell ((1,1)) and follows a pre‐programmed route. The route is a cycle: starting from ((1,1)), the robot moves only to the right (i.e. increasing the column by one) or down (i.e. increasing the row by one). When the robot is at ((i, m)) and moves right it wraps around to ((i,1)), and when it is at ((n, j)) and moves down it wraps around to ((1,j)). In a valid plan the robot passes through every cell exactly once before its next move would return it to ((1,1)) (thus forming a Hamiltonian cycle on the toroidal grid).
However, after purchasing new furniture, some cells are blocked by obstacles which the robot cannot pass. Consequently in every pre‐calculated plan the robot, following its fixed route, will eventually run into an obstacle and stop. For a plan (S) denote (f(S)) as the number of cells the robot passes (starting at ((1,1)) and counting each cell it enters) before it collides with an obstacle (the cell containing the obstacle is not counted).
You are given the grid dimensions (n) and (m) and the coordinates of the obstacle cell ((x,y)) (it is guaranteed that ((x,y) \neq (1,1))). In the original (obstacle–free) pre‐calculated plans, the robot would cover every cell exactly once before returning to ((1,1)). Now, for all these valid plans, compute the sum of (f(S)) over all different plans (S). Two plans are considered different if their order of visited cells is different.
It is guaranteed that the grid and movement restrictions are such that at least one valid plan exists, and under the new arrangement the robot will hit the obstacle in every plan.
inputFormat
The input consists of a single line containing four integers separated by spaces: (n), (m), (x), and (y), where (n) and (m) ((1 \leq n, m \leq 6)) represent the dimensions of the grid and ((x,y)) (with (1 \leq x \leq n,; 1 \leq y \leq m) and ((x,y)\neq (1,1))) is the coordinate of the obstacle cell.
outputFormat
Output a single integer, which is the sum of (f(S)) over all valid Hamiltonian cycle plans (S) (each plan is a sequence of cells starting at ((1,1)) that would cover all (n \times m) cells exactly once and then return to ((1,1)) if continued).
sample
2 2 1 2
1