#P12106. [NWRRC2024] Brick in the Wall, Part 2

[NWRRC2024] Brick in the Wall, Part 2

Description

Barrett has discovered an ancient maze under his house. It has the shape of an n×mn \times m grid, where some cells are empty, while others are blocked. It is possible to walk from one empty cell to another if they share a side. Two of the empty cells are an entrance and an exit, and it is possible to reach one from the other by walking through empty cells.

Barrett wants to isolate his house by building a wall inside the maze, blocking some cells to make the exit unreachable from the entrance. The wall should be straight and oriented either vertically or horizontally. Specifically, a wall of length kk will block a consecutive row or column of exactly kk cells. The wall may not contain the entrance, the exit, or any already blocked cells.

Help Barrett determine the minimum possible length of the wall.

Input Format

Each test contains multiple test cases. The first line contains the number of test cases tt (1t1051 \le t \le 10^5). The description of the test cases follows.

The first line of each test case contains two integers nn and mm, denoting the height and the width of the~maze (2n,m10002 \le n, m \le 1000).

The ii-th of the following nn lines contains mm characters and describes the ii-th row of the maze, where:

  • .\texttt{.} denotes an empty cell;
  • #\texttt{\#} denotes a blocked cell;
  • s\texttt{s} denotes an entrance cell;
  • f\texttt{f} denotes an exit cell.

The maze contains exactly one entrance cell and exactly one exit cell, and it is possible to reach one from the other by walking through empty cells.

It is guaranteed that the sum of nmn \cdot m over all test cases does not exceed 10610^6.

Output Format

For each test case, print the minimum length of the wall required to make the exit unreachable from the entrance.

If it is impossible to build such a wall, print 1-1 instead.

3
3 3
s.#
...
#.f
6 7
..#.#..
s..#..#
....#f.
#..#...
#......
#.....#
2 2
s.
.f
1
2
-1