Under construction

Still being built. Things may change

Lucky☆Hanbyul

Time limit2sMemory limit1024 MB

Summary
Find the most gifts Hanbyul can collect while walking a shortest path to a reachable exit, given that the other people move optimally to meet Hanbyul.
Level

Medium7 of 10

Topics
BFS, Shortest path, Dynamic programming, Graph
Solved
No attempts yet

Problem

Hanbyul is very lucky!

Hanbyul wants to escape a maze that has walls, other people, and several exits.

Inside the maze, Hanbyul and the other people can each move one cell up, down, left, or right at every moment. People other than Hanbyul may also stay still. Moving into a wall cell or out of the grid is impossible. Several people can be in the same cell.

Every person except Hanbyul holds one gift for Hanbyul. If Hanbyul and a person holding a gift are in the same cell, that person gives the gift to Hanbyul.

Hanbyul picks one of the exits that Hanbyul can reach, picks one of the shortest paths to it, and follows that path. The other people know Hanbyul's path and move along the optimal routes to give Hanbyul their gifts.

When Hanbyul moves from one cell to another, Hanbyul receives gifts from the people already in the arrived cell and from the people who arrived in that cell at the same time as Hanbyul. If the arrived cell is the exit Hanbyul chose at the start, Hanbyul escapes the maze immediately. The other people do not escape the maze even if they reach an exit.

Hanbyul is very lucky, so Hanbyul always receives the maximum possible number of gifts. Find the maximum number of gifts Hanbyul can receive when Hanbyul chooses an exit and a shortest path appropriately and the other people move appropriately.

Input

The first line contains the height NN and width MM of the maze, separated by a space. (1≤N,M1 \leq N, M, N×M≤100 000N \times M \leq 100\,000)

The next NN lines give the maze as strings of length MM.

In the strings, H marks Hanbyul and appears exactly once in the maze.

In the strings, P marks a person other than Hanbyul and appears at least 1 time and at most 100 times in the maze.

In the strings, # marks an exit and appears at most 100 times in the maze.

In the strings, . marks an empty cell.

In the strings, X marks a wall.

At least one exit that Hanbyul can reach is guaranteed to exist.

Output

Print the maximum number of gifts Hanbyul can receive.

Examples4

  1. Example 1

    Input
    4 3
    #..
    ..H
    .P.
    .P.
    
    Expected output
    1
    
  2. Example 2

    Input
    4 3
    #X.
    .XH
    .P.
    .P.
    
    Expected output
    2
    
  3. Example 3

    Input
    4 4
    #PPH
    X..P
    PPPP
    #XXX
    
    Expected output
    7
    
  4. Example 4

    Input
    1 5
    H#.P#
    
    Expected output
    1