P13937 [Lanqiao Cup 2022 Senior Java B] Pulling Boxes
Description
Pushing boxes is a classic video game. Alice likes it a lot, but she is a little tired of it, so now she wants to design a pulling-boxes game.
The pulling-boxes game requires the player to move a character up, down, left and right on an $N \times M$ grid map, and to pull the box to the goal in order to win.
Now Alice wants to know, for a given terrain (that is, the positions of all walls), how many different solvable initial positions there are.
**Initial position** is defined as follows:
1. An initial position consists of various elements arranged in an $N \times M$ rectangular grid, and every cell contains exactly one element. The possible elements are: empty ground, wall, person, box and goal.
2. An initial position contains exactly one person.
3. An initial position contains exactly one box.
4. An initial position contains exactly one goal.
**Solvable** is defined as follows:
By moving the person a finite number of times (the box may be pulled while moving), the box can reach the cell where the goal is.
**Move** is defined as follows:
In one move, the person may move to an adjacent cell (one of up, down, left and right), provided that the following conditions hold:
1. The person can never move outside the $N \times M$ grid.
2. The person can never move onto a wall or onto the box.
3. The person may move onto empty ground or onto the goal.
**Pulling the box** is defined as follows:
During one legal move, if the cell adjacent to the person's starting cell in the direction opposite to the moving direction contains exactly the box, the person may pull the box along, so that the box moves to the cell where the person started this move.
Even if the conditions hold, the person may also simply move without pulling the box.
Input Format
The first line contains two positive integers $N$ and $M$, the size of the grid.
The next $N$ lines each contain $M$ space-separated integers $0$ or $1$, describing the given terrain. Here $1$ denotes a wall, and $0$ denotes an unknown element; an unknown element may be the person, the box, empty ground or the goal, but cannot be a wall.
Output Format
Output one positive integer, the number of solvable initial positions.
Explanation/Hint
**Sample Explanation**
The $13$ solvable initial positions are shown below. In the diagrams, `P` is the person, `B` is the box, `G` is the goal, `E` is empty ground and `W` is a wall.
```
PGBE
WWWE
```
```
PGEB
WWWE
```
```
PEGB
WWWE
```
```
BPGE
WWWE
```
```
EPGB
WWWE
```
```
BGPE
WWWE
```
```
EGPB
WWWE
```
```
BGEP
WWWE
```
```
BEGP
WWWE
```
```
EBGP
WWWE
```
```
BGEE
WWWP
```
```
BEGE
WWWP
```
```
EBGE
WWWP
```
**Constraints**
For $30\%$ of the test cases, $N, M \leq 3$.
For $100\%$ of the test cases, $0 < N, M \leq 10$.
Translated by QwenWork