Under construction

Still being built. Things may change

Brick in the Wall, Part 2

Time limit5sMemory limit2048 MB

Summary
Given a grid maze with an entrance s and exit f, find the shortest straight horizontal or vertical wall that separates them, or print -1.
Level

Medium6 of 10

Topics
Graph, BFS, Implementation
Solved
No attempts yet

Statement

Barrett has discovered an ancient maze under his house. It is an n×mn \times m grid where some cells are empty and others are blocked. Two empty cells are adjacent if they share a side. One empty cell is the entrance and another is the exit, and you can walk from one to the other through empty cells.

Barrett wants to isolate his house by building a wall inside the maze so that the exit cannot be reached from the entrance. The wall must be straight, either vertical or horizontal. A wall of length kk blocks exactly kk consecutive cells in one row or one column. The wall may not include the entrance, the exit, or any cell that is already blocked.

Find the minimum possible length of the wall.

Input

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

The first line of each test case contains two integers nn and mm, the height and the width of the maze (2≤n,m≤10002 \le n, m \le 1000). The next nn lines each contain mm characters describing one row of the maze:

  • . is an empty cell.
  • # is a blocked cell.
  • s is the entrance.
  • f is the exit.

Each maze contains exactly one entrance and exactly one exit, and you can walk from one to the other through empty cells.

The sum of n⋅mn \cdot m over all test cases does not exceed 10610^6.

Output

For each test case, print the minimum length of a wall that makes the exit unreachable from the entrance. If no such wall can be built, print −1-1.

Examples1

  1. Example 1

    Input
    3
    3 3
    s.#
    ...
    #.f
    6 7
    ..#.#..
    s..#..#
    ....#f.
    #..#...
    #......
    #.....#
    2 2
    s.
    .f
    
    Expected output
    1
    2
    -1