# Arup Guha
# 6/29/2017
# Edit of the other bunnies problem - prints out
# the shortest path from peter to cottontail or -1
# if a path doesn't exist.

import queue

# Possible movements in the grid.
DX = [-1,0,0,1]
DY = [0,-1,1,0]

def main():

    myfile = open("bunnies.in")
    numCases = int(myfile.readline().strip())

    # Process each case.
    for loop in range(numCases):

        items = myfile.readline().split()
        numRows = int(items[0])
        numCols = int(items[1])

        # Store the grid as a list of strings.
        grid = []
        for i in range(numRows):
            grid.append(myfile.readline().strip())

        start = getPos(grid, 'P')

        # This is annoying...just want a grid -1s (not been there)
        dist = []
        for i in range(numRows):
            tmp = []
            for j in range(numCols):
                tmp.append(-1)
            dist.append(tmp)

        # Run our breadth first search from Peter.
        bfs(grid, start, dist)

        # See if we got to cotton tail and print accordingly.
        end = getPos(grid, 'C')
        print(dist[end[0]][end[1]])

    myfile.close()

def getPos(grid, ch):

    # Go through each square.
    for i in range(len(grid)):
        for j in range(len(grid[0])):

            # We found it.
            if grid[i][j] == ch:
                return (i, j)
    
def bfs(grid,start,dist):

    # Mark this spot as used - get our queue assigned.
    dist[start[0]][start[1]] = 0
    q = queue.Queue(0)
    q.put(start)

    # Run BFS until no new spots to explore.
    while not q.empty():

        # Get the next item in the queue.
        cur = q.get()
        
        # Try going in all 4 directions.
        for i in range(len(DX)):

            # Where we'd jump our current location in this direction.
            nextX = cur[0] + DX[i]
            nextY = cur[1] + DY[i]

            # We add to the queue if the square exists and we've never visited it before,
            # and it's a valid square to go to.
            if inbounds(nextX, nextY, grid) and dist[nextX][nextY] == -1 and grid[nextX][nextY] != '#':
                dist[nextX][nextY] = dist[cur[0]][cur[1]] + 1
                q.put((nextX, nextY))
            
# Returns true iff (x,y) is a valid index into grid.
def inbounds(x,y,grid):
    return x >= 0 and x < len(grid) and y >= 0 and y < len(grid[0])

# Start it up...
main()    
        
