You are given a grid with $R$ rows (numbered $1$ through $R$) and $C$ columns (numbered $1$ through $C$). Initially, each cell of this grid is either empty, contains an ant or an anteater. Each ant is moving in a fixed direction: up, down, left or right. The anteaters do not move.
The movement of ants happens in discrete steps. For example, when an ant is in the cell in the $i$-th row and $j$-th column at some point in time (in some step) and it is moving down, then in the next step, it enters the cell in the $(i+1)$-th row and $j$-th column. Two ants meet each other when they enter the same cell at the same point in time (in the same step). When ants meet, they do not interact in any way and keep moving in their fixed directions.
If an ant reaches an anteater, that anteater eats the ant, so the ant completely disappears. If an ant attempts to leave the grid, it also disappears. When two ants enter a cell containing an anteater at the same time, they are eaten before they could meet.
Calculate the total number of pairs of ants that meet each other.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $R$ and $C$.
- Each of the following $R$ lines contains a single string with length $C$. For each valid $i, j$, the $j$-th character in the $i$-th string is:
- '#' if the cell in the $i$-th row and $j$-th column of the grid contains an anteater
- 'U', 'D', 'L' or 'R' if this cell contains an ant moving up, down, left or right respectively
- '-' if this cell is empty

-----Output-----
For each test case, print a single line containing one integer — the number of pairs of ants that meet.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le R, C \le 50$
- each string contains only characters 'U', 'D', 'L', 'R', '#' and '-'

-----Example Input-----
10
3 3
R--
---
--U
1 4
R--R
2 2
--
--
1 4
R--L
1 4
-R-L
1 4
-R#L
3 3
R-D
-#-
R-U
3 3
R-D
---
R#U
3 3
-D-
R-L
-U-
1 7
RLLLLLL

-----Example Output-----
1
0
0
0
1
0
3
2
6
3

Starter code:

Solutions:
import sys

t = int(input())
# print(t)
for _ in range(t):
	n,m = map(int,input().split());
	s = [];
	for i in range(n):
		s.append(input())
	ans = []
	for i in range(n):
		ans.append([])
		for j in range(m):
			ans[i].append([])
	for i in range(n):
		for j in range(m):
			c = 0
			if s[i][j] == 'U':
				for k in range(i,-1,-1):
					if s[k][j] == '#':
						break
					ans[k][j].append(c)
					c+=1
			elif s[i][j] == 'D':
				for k in range(i,n):
					if s[k][j] == '#':
						break
					ans[k][j].append(c)
					c+=1
			elif s[i][j] == 'L':
				for k in range(j,-1,-1):
					if s[i][k] == '#':
						break
					ans[i][k].append(c)
					c+=1
			elif s[i][j] == 'R':
				for k in range(j,m):
					if s[i][k] == '#':
						break
					ans[i][k].append(c)
					c+=1
	for i in range(n):
		for j in range(m):
			ans[i][j].sort()
	res = []
	for i in range(n):
		for j in range(m):
			c= 1
			# print(ans[i][j])
			for k in range(1,len(ans[i][j])):
				# print(ans[i][j][k])
				if ans[i][j][k] == ans[i][j][k-1]:
					c+=1
				else :
					if c!=1:
						res.append(c)
					c = 1
				if k==len(ans[i][j])-1:
					if c!=1:
						res.append(c)
	pairs = 0
	# print(res)
	for i in range(len(res)):
		pairs  += ((res[i]*(res[i]-1))//2)
	
	print(pairs)

# cook your dish here
def count_ants(l, r, u, d):
    cnt = 0
    if l is False:
        cnt += 1
    if r is False:
        cnt += 1
    if u is False:
        cnt += 1
    if d is False:
        cnt += 1
    return cnt


def solve(m, row, col):
    ans = 0
    for i in range(row):
        for j in range(col):
            lw = True
            rw = True
            uw = True
            dw = True
            if m[i][j] == '#':
                continue
            for d in range(1, max(row, col)):
                cnt = 0
                if j - d < 0:
                    lw = False
                if j + d >= col:
                    rw = False
                if i - d < 0:
                    uw = False
                if i + d >= row:
                    dw = False
                if count_ants(lw, rw, uw, dw) > 2:
                    break
                if lw and j - d >= 0:
                    if m[i][j - d] == 'R':
                        cnt += 1
                    elif m[i][j-d] == '#':
                        lw = False
                if rw and j + d < col:
                    if m[i][j + d] == 'L':
                        cnt += 1
                    elif m[i][j+d] == '#':
                        rw = False

                if uw and i - d >= 0:
                    if m[i - d][j] == 'D':
                        cnt += 1
                    elif m[i-d][j] == '#':
                        uw = False

                if dw and i + d < row:
                    if m[i + d][j] == 'U':
                        cnt += 1
                    elif m[i+d][j] == '#':
                        dw = False
                if cnt > 1:
                    ans += (cnt * (cnt - 1)) // 2
    return ans


def read():
    t = int(input())
    for i in range(t):
        r, c = list(map(int, input().strip().split()))
        m = [[] for i in range(r)]
        for i in range(r):
            s = input().strip()
            m[i] = s
        ans = solve(m, r, c)
        print(ans)

read()

import copy
def AllDead(arr):
	var=1
	for x in arr:
		for y in x:
			if "U" in y or "D" in y or "L"in y or "R" in y:
				var=0
	return var
def checkMeet(arr):
	ans=0
	for x in arr:
		for y in x:
			if len(y)>=2 and '-' not in y:
				ans+=(len(y)*(len(y)-1))//2
	return ans
t=int(input())
for i in range(t):
	n,m=map(int,input().split())
	lol=[['#']]*(m+2)
	arr=[lol]
	for j in range(n):
		mo=[[x] for x in input()]
		arr+=[[['#']]+mo+[['#']]]
	arr+=[lol]
	meet=0
	while AllDead(arr)==0:
		temp=copy.deepcopy(arr)
		for x in range(1,n+1):
			for y in range(1,m+1):
				for z in arr[x][y]:
					if z=='U':
						if arr[x-1][y]==['#']:
							do_nothing=1
						elif temp[x-1][y]==['-']:
							temp[x-1][y].remove('-')
							temp[x-1][y]+=['U']
						else:
							temp[x-1][y]+=['U']
						temp[x][y].remove(z)
						if len(temp[x][y])==0:
							temp[x][y]=['-']
					if z=='D':
						if arr[x+1][y]==['#']:
							do_nothing=1
						elif temp[x+1][y]==['-']:
							temp[x+1][y].remove('-')
							temp[x+1][y]+=['D']
						else:
							temp[x+1][y]+=['D']
						temp[x][y].remove(z)
						if len(temp[x][y])==0:
							temp[x][y]=['-']
					if z=='L':
						if arr[x][y-1]==['#']:
							do_nothing=1
						elif temp[x][y-1]==['-']:
							temp[x][y-1].remove('-')
							temp[x][y-1]+=['L']
						else:
							temp[x][y-1]+=['L']
						temp[x][y].remove(z)
						if len(temp[x][y])==0:
							temp[x][y]=['-']
					if z=='R':
						if arr[x][y+1]==['#']:
							do_nothing=1
						elif temp[x][y+1]==['-']:
							temp[x][y+1].remove('-')
							temp[x][y+1]+=['R']
						else:
							temp[x][y+1]+=['R']
						temp[x][y].remove(z)
						if len(temp[x][y])==0:
							temp[x][y]=['-']
		arr=copy.deepcopy(temp)
		meet+=checkMeet(arr)
	print(meet)

readFromFile = 0
if readFromFile:
    f = open("inputSmall.txt", "r")
    T = int(f.readline())
else:
    T = int(input())

testCases = range(T)

for case in testCases:
    if (readFromFile):
        RC = [int(x) for x in f.readline().split()]
    else:
        RC = [int(x) for x in input().split()]

    R = RC[0]
    C = RC[1]

    aByCols = {}
    aByRows = {}

    uAll = []
    dAll = []
    lAll = []
    rAll = []
    
    for r in range(R):
        if(readFromFile):
            row = f.readline()
        else:
            row = input()

        for c in range(C):
            if(row[c] == '#'):
                if(r not in aByRows):
                    aByRows[r] = []                
                aByRows[r].append(c)
                if(c not in aByCols):
                    aByCols[c] = []
                aByCols[c].append(r)

            elif(row[c] == 'U'):
                uAll.append((r,c))

            elif(row[c] == 'D'):
                dAll.append((r,c))

            elif(row[c] == 'L'):
                lAll.append((r,c))

            elif(row[c] == 'R'):
                rAll.append((r,c))

    # U ant will die if # in same column, smaller row
    for x in range(len(uAll)):
        item = uAll[x]
        r = item[0]
        c = item[1]
        if (c in aByCols):
            eaters = aByCols[c]
        else:
            eaters = []
        age = R
        for y in eaters:
            if (y < r):
                age = min(age, r-y)
        uAll[x] = (item[0], item[1], age)

    # D ant will die if # in same column, larger row
    for x in range(len(dAll)):
        item = dAll[x]
        r = item[0]
        c = item[1]
        if (c in aByCols):
            eaters = aByCols[c]
        else:
            eaters = []
        age = R
        for y in eaters:
            if (y > r):
                age = min(age, y-r)
        dAll[x] = (item[0], item[1], age)

    # L ant will die if # in same row, smaller col
    for x in range(len(lAll)):
        item = lAll[x]
        r = item[0]
        c = item[1]
        if (r in aByRows):
            eaters = aByRows[r]
        else:
            eaters = []
        age = C
        for y in eaters:
            if (y < c):
                age = min(age, c-y)
        lAll[x] = (item[0], item[1], age)

    # R ant will die if # in same row, larger col
    for x in range(len(rAll)):
        item = rAll[x]
        r = item[0]
        c = item[1]
        if (r in aByRows):
            eaters = aByRows[r]
        else:
            eaters = []
        age = C
        for y in eaters:
            if (y > c):
                age = min(age, y-c)
        rAll[x] = (item[0], item[1], age)

    uBySum = {}
    uByDiff = {}
    uByCol = {}
    
    dBySum = {}
    dByDiff = {}
    dByCol = {}
    
    rBySum = {}
    rByDiff = {}
    rByRow = {}
    
    lBySum = {}
    lByDiff = {}
    lByRow = {}

    for x in uAll:
        r = x[0]
        c = x[1]
        if (r+c not in uBySum):
            uBySum[r+c] = []
        if (r-c not in uByDiff):
            uByDiff[r-c] = []
        if (c not in uByCol):
            uByCol[c] = []

        uBySum[r+c].append((r,c,x[2]))
        uByDiff[r-c].append((r,c,x[2]))
        uByCol[c].append((r,c,x[2]))

    for x in dAll:
        r = x[0]
        c = x[1]
        if (r+c not in dBySum):
            dBySum[r+c] = []
        if (r-c not in dByDiff):
            dByDiff[r-c] = []
        if (c not in dByCol):
            dByCol[c] = []

        dBySum[r+c].append((r,c,x[2]))
        dByDiff[r-c].append((r,c,x[2]))
        dByCol[c].append((r,c,x[2]))

    for x in lAll:
        r = x[0]
        c = x[1]
        if (r+c not in lBySum):
            lBySum[r+c] = []
        if (r-c not in lByDiff):
            lByDiff[r-c] = []
        if (r not in lByRow):
            lByRow[r] = []

        lBySum[r+c].append((r,c,x[2]))
        lByDiff[r-c].append((r,c,x[2]))
        lByRow[r].append((r,c,x[2]))

    for x in rAll:
        r = x[0]
        c = x[1]
        if (r+c not in rBySum):
            rBySum[r+c] = []
        if (r-c not in rByDiff):
            rByDiff[r-c] = []
        if (r not in rByRow):
            rByRow[r] = []

        rBySum[r+c].append((r,c,x[2]))
        rByDiff[r-c].append((r,c,x[2]))
        rByRow[r].append((r,c,x[2]))

    uSums = set(uBySum.keys())
    uDiffs = set(uByDiff.keys())
    uCols = set(uByCol.keys())
    dSums = set(dBySum.keys())
    dDiffs = set(dByDiff.keys())
    dCols = set(dByCol.keys())
    rSums = set(rBySum.keys())
    rDiffs = set(rByDiff.keys())
    rRows = set(rByRow.keys())
    lSums = set(lBySum.keys())
    lDiffs = set(lByDiff.keys())
    lRows = set(lByRow.keys())

    total = 0

    ## same sums: possible collision between U and L
    candidates = uSums & lSums
    for cc in candidates:
        r1 = [(x[0], 1, x[2]) for x in uBySum[cc]]
        r2 = [(x[0], 0, x[2]) for x in lBySum[cc]]
        rTot = r1 + r2
        rTot.sort()

        # Collision only when row of U > row of L
        # both parties survive
        zeros = []
        for i in range(len(rTot)):
            item = rTot[i]
            if (item[1] == 1):
                for j in zeros:
                    if (item[0] - j[0] < j[2]) and (item[0] - j[0] < item[2]):
                        total = total + 1
            elif (item[1] == 0):
                zeros.append(item)

    ## same sums: possible collision between D and R
    candidates = dSums & rSums
    for cc in candidates:
        r1 = [(x[0], 1, x[2]) for x in rBySum[cc]]
        r2 = [(x[0], 0, x[2]) for x in dBySum[cc]]
        rTot = r1 + r2
        rTot.sort()

        # Collision only when row of R > row of D
        # both parties survive
        zeros = []
        for i in range(len(rTot)):
            item = rTot[i]
            if (item[1] == 1):
                for j in zeros:
                    if (item[0] - j[0] < j[2]) and (item[0] - j[0] < item[2]):
                        total = total + 1
            elif (item[1] == 0):
                zeros.append(item)

    ## same diffs: possible collision between U and R
    candidates = uDiffs & rDiffs
    for cc in candidates:
        r1 = [(x[0], 1, x[2]) for x in uByDiff[cc]]
        r2 = [(x[0], 0, x[2]) for x in rByDiff[cc]]
        rTot = r1 + r2
        rTot.sort()

        # Collision only when row of U > row of R
        # both parties survive
        zeros = []
        for i in range(len(rTot)):
            item = rTot[i]
            if (item[1] == 1):
                for j in zeros:
                    if (item[0] - j[0] < j[2]) and (item[0] - j[0] < item[2]):
                        total = total + 1
            elif (item[1] == 0):
                zeros.append(item)

    ## same diffs: possible collision between D and L
    candidates = dDiffs & lDiffs
    for cc in candidates:
        r1 = [(x[0], 1, x[2]) for x in lByDiff[cc]]
        r2 = [(x[0], 0, x[2]) for x in dByDiff[cc]]
        rTot = r1 + r2
        rTot.sort()

        # Collision only when row of L > row of D
        # both parties survive
        zeros = []
        for i in range(len(rTot)):
            item = rTot[i]
            if (item[1] == 1):
                for j in zeros:
                    if (item[0] - j[0] < j[2]) and (item[0] - j[0] < item[2]):
                        total = total + 1
            elif (item[1] == 0):
                zeros.append(item)

    ## same cols: possible collision between D and U
    candidates = dCols & uCols
    for cc in candidates:
        r1 = [(x[0], 1, x[2]) for x in uByCol[cc]]
        r2 = [(x[0], 0, x[2]) for x in dByCol[cc]]
        rTot = r1 + r2
        rTot.sort()

        # Collision only when row of U > row of D,
        # distance is even
        # both parties survive
        zeros = []
        for i in range(len(rTot)):
            item = rTot[i]
            if (item[1] == 1):
                for j in zeros:
                    if ((item[0] - j[0]) % 2 == 0) and (item[0] - j[0] < 2*j[2]) and (item[0] - j[0] < 2*item[2]):
                        total = total + 1
            elif (item[1] == 0):
                zeros.append(item)

    ## same rows: possible collision between L and R
    candidates = lRows & rRows
    for cc in candidates:
        r1 = [(x[1], 1, x[2]) for x in lByRow[cc]]
        r2 = [(x[1], 0, x[2]) for x in rByRow[cc]]
        rTot = r1 + r2
        rTot.sort()

        # Collision only when col of L > col of R, 
        # distance is even
        # both parties survive
        zeros = []
        for i in range(len(rTot)):
            item = rTot[i]
            if (item[1] == 1):
                for j in zeros:
                    if ((item[0] - j[0]) % 2 == 0) and (item[0] - j[0] < 2*j[2]) and (item[0] - j[0] < 2*item[2]):
                        total = total + 1
            elif (item[1] == 0):
                zeros.append(item)

    print(total)

def nCr(n, r): 
  
    return (fact(n) / (fact(r) * fact(n - r))) 

def fact(n):
    res = 1
      
    for i in range(2, n+1): 
        res = res * i 
          
    return res 


while True:
    try:
        for _ in range(int(input())):
            r,c = map(int,input().split())
            arena = [[i for i in input().strip()] for j in range(r)]

            #print(*arena,sep='\n')

            antsInitialPositions = []
            antsDirection=[]
            antEaterPositions = []
            for i in range(r):
                for j in range(c):
                    if arena[i][j] in ['R','U','D','L']:
                        antsInitialPositions.append([i,j])
                        antsDirection.append(arena[i][j])
                    elif arena[i][j] == '#':
                        antEaterPositions.append([i,j])

            #print(antsInitialPositions)
            #print(antEaterPositions)

            antCount = len(antsInitialPositions)
            grid = [[{} for j in range(c)] for i in range(r)]

            for current in range(antCount):
                i,j = antsInitialPositions[current]
                direction = antsDirection[current]
                movei,movej = i,j
                if direction == 'D':
                    steps = 0
                    while movei<r and arena[movei][movej] != '#':
                        steps = abs(i-movei)
                        if steps in grid[movei][movej]:
                            grid[movei][movej][steps]+=1
                        else:
                            grid[movei][movej][steps]=1
                        movei+=1
                elif direction == 'U':
                    steps=0
                    while movei>=0 and arena[movei][movej] != '#':
                        steps = abs(i-movei)
                        #print("steps counted ", steps,movei,movej)
                        if steps in grid[movei][movej]:
                            #print("already there in dict")
                            grid[movei][movej][steps]+=1
                        else:
                            grid[movei][movej][steps]=1
                        movei-=1
                elif direction == 'L':
                    steps=0
                    while movej>=0 and arena[movei][movej] != '#':
                        steps = abs(j-movej)
                        if steps in grid[movei][movej]:
                            grid[movei][movej][steps]+=1
                        else:
                            grid[movei][movej][steps]=1
                        movej-=1
                elif direction == 'R':
                    steps=0
                    while movej<c and arena[movei][movej] != '#':
                        steps = abs(j-movej)
                        if steps in grid[movei][movej]:
                            grid[movei][movej][steps]+=1
                        else:
                            grid[movei][movej][steps]=1
                        movej+=1
            #print(*grid,sep='\n')
            meetings=0
            for i in range(r):
                for j in range(c):
                    for meets in grid[i][j].values():
                        if meets>=2:
                            meetings+=nCr(meets,2)
            print(int(meetings))


    except (ValueError,EOFError) as e:
        break

def nCr(n, r): 
  
    return (fact(n) / (fact(r) * fact(n - r))) 

def fact(n):
    res = 1
      
    for i in range(2, n+1): 
        res = res * i 
          
    return res 


while True:
    try:
        for _ in range(int(input())):
            r,c = map(int,input().split())
            arena = [[i for i in input().strip()] for j in range(r)]

            #print(*arena,sep='\n')

            antsInitialPositions = []
            antsDirection=[]
            antEaterPositions = []
            for i in range(r):
                for j in range(c):
                    if arena[i][j] in ['R','U','D','L']:
                        antsInitialPositions.append([i,j])
                        antsDirection.append(arena[i][j])
                    elif arena[i][j] == '#':
                        antEaterPositions.append([i,j])

            #print(antsInitialPositions)
            #print(antEaterPositions)

            antCount = len(antsInitialPositions)
            grid = [[{} for j in range(c)] for i in range(r)]

            for current in range(antCount):
                i,j = antsInitialPositions[current]
                direction = antsDirection[current]
                movei,movej = i,j
                if direction == 'D':
                    steps = 0
                    while movei<r and arena[movei][movej] != '#':
                        steps = abs(i-movei)
                        if steps in grid[movei][movej]:
                            grid[movei][movej][steps]+=1
                        else:
                            grid[movei][movej][steps]=1
                        movei+=1
                elif direction == 'U':
                    steps=0
                    while movei>=0 and arena[movei][movej] != '#':
                        steps = abs(i-movei)
                        #print("steps counted ", steps,movei,movej)
                        if steps in grid[movei][movej]:
                            #print("already there in dict")
                            grid[movei][movej][steps]+=1
                        else:
                            grid[movei][movej][steps]=1
                        movei-=1
                elif direction == 'L':
                    steps=0
                    while movej>=0 and arena[movei][movej] != '#':
                        steps = abs(j-movej)
                        if steps in grid[movei][movej]:
                            grid[movei][movej][steps]+=1
                        else:
                            grid[movei][movej][steps]=1
                        movej-=1
                elif direction == 'R':
                    steps=0
                    while movej<c and arena[movei][movej] != '#':
                        steps = abs(j-movej)
                        if steps in grid[movei][movej]:
                            grid[movei][movej][steps]+=1
                        else:
                            grid[movei][movej][steps]=1
                        movej+=1
            #print(*grid,sep='\n')
            meetings=0
            for i in range(r):
                for j in range(c):
                    for meets in grid[i][j].values():
                        if meets>=2:
                            meetings+=nCr(meets,2)
            print(int(meetings))


    except (ValueError,EOFError) as e:
        break

def find_next(arr):
    ans=[[set() for i in range(len(arr[0]))] for j in range(len(arr))]
    for i in range(len(arr)):
        for j in range(len(arr[0])):
            if j>0:
                if 'R' in arr[i][j-1] and '#' not in arr[i][j]:
                    ans[i][j].add('R')
            if j<len(arr[0])-1:
                if 'L' in arr[i][j+1] and '#' not in arr[i][j]:
                    ans[i][j].add('L')
            if i>0:
                if 'D' in arr[i-1][j] and '#' not in arr[i][j]:
                    ans[i][j].add('D')
            if i<len(arr)-1:
                if 'U' in arr[i+1][j] and '#' not in arr[i][j]:
                    ans[i][j].add('U')
            if '#' in arr[i][j]:
                ans[i][j].add("#")
    return ans

def cal(arr):
    ans=0
    for i in range(len(arr)):
        for j in range(len(arr[0])):
            n=len(arr[i][j])
            ans+=n*(n-1)//2
    return ans
t=int(input())
for _ in range(t):
    r,c=list(map(int,input().split()))
    arr=[]
    for i in range(r):
        toadd=list(map(set,list(input())))
        arr+=[toadd]
    ans=0
    for i in range(max(r,c)):
        arr=find_next(arr)
        ans+=cal(arr)
    print(ans)
        


t = int(input())
for x in range(t):
    r, c = map(int, input().split())
    antU = []
    antD = []
    antR = []
    antL = []
    anteater = []
    j = 0
    for y in range(r):
        s = input()
        i = 0
        for z in s:
            if(z == 'U'):
                antU.append([j, i, 0, i])
            elif(z == 'D'):
                antD.append([j, i, r - 1, i])
            elif(z == 'R'):
                antR.append([j, i, j, c - 1])
            elif(z == 'L'):
                antL.append([j, i, j, 0])
            elif(z == '#'):
                anteater.append([j, i])
            i = i + 1
        j = j + 1
    for y in anteater:
        for z in antU:
            if(y[1] == z[1] and z[0] > y[0] and z[2] <= y[0]):
                z[2] = y[0] + 1     
        for z in antD:
            if(y[1] == z[1] and z[0] < y[0] and z[2] >= y[0]):
                z[2] = y[0] - 1
        for z in antR:
            if(y[0] == z[0] and z[1] < y[1] and z[3] >= y[1]):
                z[3] = y[1] - 1
        for z in antL:
            if(y[0] == z[0] and z[1] > y[1] and z[3] <= y[1]):
                z[3] = y[1] + 1
    total = 0
    for y in antU:
        for z in antD:
            if(y[1] == z[1] and y[2] <= z[2] and y[0] > z[0]):
                if((y[0] - z[0]) % 2 == 0):
                    total = total + 1
        for z in antR:
            if(y[1] - z[1] == y[0] - z[0]):
                if(y[2] <= z[0] and z[3] >= y[1]):
                    if(y[0] > z[0] and y[1] > z[1]):
                        total = total + 1
        for z in antL:
            if(y[1] - z[1] == z[0] - y[0]):
                if(z[3] <= y[1] and y[2] <= z[0]):
                    if(y[0] > z[0] and y[1] < z[1]):
                        total = total + 1
    for y in antL:
        for z in antR:
            if((y[1] - z[1]) % 2 == 0):
                if(y[0] == z[0] and y[3] <= z[3] and y[1] > z[1]):
                    total = total + 1
        for z in antD:
            if(y[0] - z[0] == y[1] - z[1]):
                if(y[3] <= z[1] and z[2] >= y[0]):
                    if(y[0] > z[0] and y[1] > z[1]):
                        total = total + 1
    for y in antD:
        for z in antR:
            if(y[0] - z[0] == z[1] - y[1]):
                if(z[3] >= y[1] and y[2] >= z[0]):
                    if(y[0] < z[0] and y[1] > z[1]):
                        total = total + 1
    print(total)

# cook your dish here
for i in range(int(input())):
    r,c = [int(a) for a in input().split()]
    a = []
    for i in range(r):
        a.append(input())
    
    n = max(r,c)
    lst = [0 for i in range(n)]
    complete_list = []
    for i in range(r):
        z = []
        for j in range(c):
            z.append(lst.copy())
        complete_list.append(z)
    
    for i in range(r):
        for j in range(c):
            if a[i][j] == 'R':
                l = 1
                for p in range(j+1, c):
                    if a[i][p] == '#':
                        break
                    complete_list[i][p][l] += 1
                    l += 1

            elif a[i][j] == 'L':
                l = 1
                for p in range(j-1,-1,-1):
                    if a[i][p] == '#':
                        break
                    complete_list[i][p][l] += 1
                    l += 1

            elif a[i][j] == 'D':
                l = 1
                for p in range(i+1,r):
                    if a[p][j] == '#':
                        break
                    complete_list[p][j][l] += 1
                    l += 1

            elif a[i][j] == 'U':
                l = 1
                for p in range(i-1,-1,-1):
                    if a[p][j] == '#':
                        break
                    complete_list[p][j][l] += 1
                    l += 1

    ans = 0
    for i in range(r):
        for j in range(c):
            for p in range(n):
                if complete_list[i][j][p] == 2:
                    ans += 1
                elif complete_list[i][j][p] == 3:
                    ans += 3
                elif complete_list[i][j][p] == 4:
                    ans += 6          
    print(ans)
            

            

    

import copy
for t in range(int(input())):
    r,c = list(map(int,input().split()))
    grid = []
    cpy = []
    for i in range(r):
        grid.append(list(input()))
    change = True
    ans = 0
    while(change):
        cpy = [["" for i in range(c)] for j in range(r)]
        change = False
        for i in range(r):
            for j in range(c):
                for ele in grid[i][j]:
                    if(ele=="D" and i<r-1):
                        change = True
                        if(grid[i+1][j]!="#"):
                            cpy[i+1][j] += "D"
                    elif(ele=="U" and i>0):
                        change = True
                        if(grid[i-1][j]!='#'):
                            cpy[i-1][j] += "U"
                    elif(ele=="R" and j<c-1):
                        change = True
                        if(grid[i][j+1]!="#"):
                            cpy[i][j+1] += "R"
                    elif(ele=="L" and j>0):
                        change = True
                        if(grid[i][j-1]!='#'):
                            cpy[i][j-1] += "L"
                    elif(ele=="#"):
                        cpy[i][j] = "#"
        for i in range(r):
            for j in range(c):
                s = cpy[i][j]
                ans += len(s)*(len(s)-1)/2
                grid[i][j] = s
    print(int(ans))

for t in range(int(input())):
    r,c = list(map(int,input().split()))
    grid = []
    cpy = []
    for i in range(r):
        grid.append(list(input()))
    change = True
    ans = 0
    while(change):
        cpy = [["" for i in range(c)] for j in range(r)]
        change = False
        for i in range(r):
            for j in range(c):
                for ele in grid[i][j]:
                    if(ele=="D" and i<r-1):
                        change = True
                        if(grid[i+1][j]!="#"):
                            cpy[i+1][j] += "D"
                    elif(ele=="U" and i>0):
                        change = True
                        if(grid[i-1][j]!='#'):
                            cpy[i-1][j] += "U"
                    elif(ele=="R" and j<c-1):
                        change = True
                        if(grid[i][j+1]!="#"):
                            cpy[i][j+1] += "R"
                    elif(ele=="L" and j>0):
                        change = True
                        if(grid[i][j-1]!='#'):
                            cpy[i][j-1] += "L"
                    elif(ele=="#"):
                        cpy[i][j] = "#"
        for i in range(r):
            for j in range(c):
                s = cpy[i][j]
                ans += len(s)*(len(s)-1)/2
                grid[i][j] = s
    print(int(ans))
                
                
                    
                
                
                    


def sumOfN(n): return n*(n-1)//2

def display():
	for i in range(r):
		for j in range(c):
			print(grid[i][j], end =" ")
		print()
	
	print()

for t in range(int(input())):
	r,c = map(int,input().split())
	grid = []
	pairs = 0
	for i in range(r):
		to_add = []
		for x in input().strip(): to_add.append([x,1])
		grid.append(to_add)	

	#display()
	steps = max(r,c)
	for _ in range(steps):
		for i in range(r):
			for j in range(c):
				s = grid[i][j][0][:grid[i][j][1]]
				if s=="#" or s=="-":
					continue
				
				for ants in s:
					if ants=="U":
						if i>0:
							if grid[i-1][j][0]!="#": grid[i-1][j][0] += "U"
					elif ants=="D":
						if i<r-1:
							if grid[i+1][j][0]!="#": grid[i+1][j][0] += "D"
					elif ants=="L":
						if j>0:
							if grid[i][j-1][0]!="#": grid[i][j-1][0] += "L"
					elif ants=="R":
						if j<c-1:
							if grid[i][j+1][0]!="#": grid[i][j+1][0] += "R"

				grid[i][j][0] = ("-" if len(grid[i][j][0])==grid[i][j][1] else grid[i][j][0][grid[i][j][1]:])

		for i in range(r):
			for j in range(c):
				if grid[i][j][0].lstrip('-')!="":
					grid[i][j][0] = grid[i][j][0].lstrip('-')
					pairs += sumOfN(len(grid[i][j][0]))
				grid[i][j][1] = len(grid[i][j][0])
		
		#display()
	print(pairs)

# cook your dish here
'''test=int(input())
for _ in range(test):
    r,c=map(int,input().split())
    
    pathant=[]
    rc=[]
    for i in range(r):
        ci=list(map(str,input()))
        rc.append(ci)
        for j in range(c):
            if(ci[j]!='#' and ci[j]!='-'):
                pathant.append([ci[j],i,j])
            
    count=0
    parr=[]
    print(pathant)
    for i in range(len(pathant)):
        temp=[]
        if(pathant[i][0]=='L'):
            count=pathant[i][2]
            for j in range(count,-1,-1):
                if(rc[pathant[i][1]][j]=='#'):
                    break
                temp.append([pathant[i][1],j])
            parr.append(temp)
        if(pathant[i][0]=='R'):
            count=pathant[i][2]
            for j in range(count,c):
                if(rc[pathant[i][1]][j]=='#'):
                    break
                temp.append([pathant[i][1],j])
            parr.append(temp)
        if(pathant[i][0]=='U'):
            count=pathant[i][1]
            for j in range(count,-1,-1):
                if(rc[j][pathant[i][2]]=='#'):
                    break
                temp.append([j,pathant[i][2]])
            parr.append(temp)
        if(pathant[i][0]=='D'):
            count=pathant[i][1]
            for j in range(count,r):
                if(rc[j][pathant[i][2]]=='#'):
                    break
                temp.append([j,pathant[i][2]])
            parr.append(temp)
    print(parr)
    length=len(parr)
    noe=[0]*len(parr)
    nop=0
    pointer=0
    lim=max(r,c)
    temp=[]
    while pointer < lim:
        temp=[]
        for x in range(length):
            if(pointer<=len(parr[x])):
                temp.append(parr[x][pointer])'''
                
from collections import defaultdict as df
t=int(input())
for x in range(t):
    r,c=list(map(int,input().split()))
    p=df(list)
    a=[[0]*c for i in range(r)]
    for i in range(r):
        s=input().rstrip()
        for j in range(c):
            a[i][j]=s[j]
    for i in range(r):
        for j in range(c):
            timer=0
            if a[i][j]=='U':
                
                for k in range(i-1,-1,-1):
                    if a[k][j]!='#':
                        timer+=1
                        p[str(k)+' '+str(j)].append(timer)
                    else:
                        break
            if a[i][j]=='R':
                for k  in range(j+1,c):
                    if a[i][k]!='#':
                        timer+=1
                        p[str(i)+' '+str(k)].append(timer)
                    else:
                        break
            if a[i][j]=='D':
                for k in range(i+1,r):
                    if a[k][j]!='#':
                        timer+=1
                        p[str(k)+' '+str(j)].append(timer)
                    else:
                        break
            if a[i][j]=='L':
                for  k in range(j-1,-1,-1):
                    if a[i][k]!='#':
                        timer+=1
                        p[str(i)+' '+str(k)].append(timer)
                    else:
                        break
    #print(p)
    total=0
    #print(p)
    for i in p:
        y=set(p[i])
        for j in y:
            if p[i].count(j)>1:
                n1=p[i].count(j)
                total+=(n1*(n1-1))//2
    print(total)
                
                
        
                    
                        
                        
                
        
            
    
        
            
        
        
        
                
            
            
        
    
    

# cook your dish here
from collections import defaultdict
from math import factorial
t = int(input())

for _ in range(t):
    n,m = map(int,input().split())
    l = []
    hash = defaultdict(int)
    for i in range(n):
        k = list(input())
        l.append(k)
    ans = 0
    for i in range(n):
        for j in range(m):
            count = 0
            if l[i][j] == 'R':
                x = i
                y = j

                while y<m:
                    if l[x][y]!='#':
                        hash[(count,x,y)]+=1
                    else:
                        break

                    count+=1
                    y+=1

            elif l[i][j] == 'L':
                    x = i
                    y = j
                    count = 0
                    while y>=0:
                       if l[x][y]!='#':
                          hash[(count,x,y)]+=1
                       else:
                           break

                       count+=1


                       y-=1
            elif l[i][j] == 'U':
                x = i
                y = j
                count = 0
                while x>=0:
                    if l[x][y]!='#':
                        hash[(count,x,y)]+=1
                    else:
                        break

                    count+=1
                    x-=1
            elif l[i][j] == 'D' :
                x = i
                y = j
                count = 0
                while x<n:
                    if l[x][y]!='#':
                        hash[(count,x,y)]+=1
                    else:
                        break

                    count+=1
                    x+=1


    for i in hash.keys():

        z = hash[i]
        if z>1:
          ans +=  factorial(z)//((factorial(z-2))*factorial(2))

    # print(hash.keys())
    print(ans)






for _ in range(int(input())):
    r,c=map(int,input().split())
    d=[]
    s=0
    for _ in range(r):
        a=input()
        a=[i for i in a]
        d.append(a)
    for i in range(r):
        for j in range(c):
            if d[i][j]=='R':
                for k in range(j,c):
                    if d[i][k]=='#':break
                    elif d[i][k]=='L' and not((k-j) & 1):s+=1
                l=i+1
                k=j+1
                while k<c and l<r:
                    f=0
                    if d[l][k]=='U':
                        for m in range(j,k+1):
                            if d[i][m]=='#':
                                f=1
                                break
                        if f==0:
                         for m in range(i,l+1):
                             if d[m][k]=='#':
                                 f=1
                                 break
                        if f==0:s+=1
                    k+=1
                    l+=1
            elif d[i][j]=='L':
                l=i+1
                k=j-1
                while l<r and k>-1:
                  if d[l][k]=='U':
                    f=0
                    for m in range(j,k-1,-1):
                        if d[i][m] == '#':
                            f = 1
                            break
                    if f == 0:
                        for m in range(i,l+1):
                            if d[m][k] == '#':
                                f=1
                                break
                    if f == 0: s += 1
                  l+=1
                  k-=1
            elif d[i][j]=='D':
                for m in range(i,r):
                    if d[m][j]=='#':break
                    elif d[m][j]=='U' and not((m-i) & 1):s+=1
                l=i+1
                k=j+1
                while l<r and k<c:
                    f=0
                    if d[l][k]=='L':
                        for m in range(i,l+1):
                            if d[m][j] == '#':
                                f = 1
                                break
                        if f == 0:
                            for m in range(j,k+1):
                                if d[l][m] == '#':
                                    f = 1
                                    break
                        if f == 0: s += 1
                    l += 1
                    k += 1
                l=i+1
                k=j-1
                while l<r and k>-1:
                    f=0
                    if d[l][k]=='R':
                        for m in range(i,l+1):
                            if d[m][j]=='#':
                                f=1
                                break
                        if f==0:
                            for m in range(k,j+1):
                                if d[l][m]=='#':
                                    f=1
                                    break
                        if f==0:s+=1
                    l+=1
                    k-=1
    print(s)

t=int(input())
for i in range(t):
    r,c=map(int,input().split())
    arr=[[""for x in range(c)]for y in range(r)]
    for j in range(r):
        arr[j]=list(str(input()))
    # for j in range(r):
    #     print(arr[j])
    # anrnum=0
    anr=['U','D','L','R']
    # for j in range(r):
    #     for k in range(c):
    #         if(arr[j][k]in anr):
    #             anrnum+=1
    meet=0
    pos=[[[0 for z in range(c)] for y in range(r)] for x in range(max(r,c))]
    j=0
    k=0
    while j <r:
        j_init = j
        # if(j==r):
            # print("Fault:"+str(j))
        k=0
        while k <c:
            k_init = k
            # if(j==r or k==c):
            #     print("Fault:"+str(j)+" "+str(k))
            # print(str(j) + " " + str(k))
            if(arr[j][k] in anr):

                for z in range(max(r, c)):
                    if(j==r or k==c or arr[j][k]=="#" or k==-1 or j==-1):
                        break
                    if(pos[z][j][k]>0):
                        meet+=pos[z][j][k]
                    # else:
                        # print(str(z) + " " + str(j) + " " + str(k))
                    pos[z][j][k]+=1
                    if(arr[j_init][k_init]=='D'):
                        j+=1
                    elif(arr[j_init][k_init]=='U'):
                        j-=1
                    elif (arr[j_init][k_init] == 'L'):
                        k -= 1
                    elif (arr[j_init][k_init] == 'R'):
                        k += 1
            k=k_init+1
            j = j_init
        j=j_init+1
    print(meet)
    # for iter in range(max(r,c)):
    #     print(pos[iter])





for _ in range(int(input())):
	r, c = map(int, input().split())
	m = [[*input()] for _ in range(r)]

	ans = 0
	p = []

	for i in range(r):
		for j in range(c):
			if m[i][j] in 'UDLR':
				p.append([i, j, m[i][j]])

	from collections import Counter

	for i in range(max(r, c) + 1):
		z = Counter([tuple(i[:2]) for i in p])
		for j in z.values():
			ans += (j * (j - 1)) // 2

		d = set()

		for j in range(len(p)):
			if p[j][2] == 'U':
				if p[j][0] > 0 and m[p[j][0] - 1][p[j][1]] != '#':
					p[j][0] -= 1
				else:
					d.add(j)
			elif p[j][2] == 'R':
				if p[j][1] < c - 1 and m[p[j][0]][p[j][1] + 1] != '#':
					p[j][1] += 1
				else:
					d.add(j)
			elif p[j][2] == 'L':
				if p[j][1] > 0 and m[p[j][0]][p[j][1] - 1] != '#':
					p[j][1] -= 1
				else:
					d.add(j)
			else:
				if p[j][0] < r - 1 and m[p[j][0] + 1][p[j][1]] != '#':
					p[j][0] += 1
				else:
					d.add(j)

		p = [p[i] for i in set([*range(len(p))]) - d]

	print(ans)

# your code goes here
# cook your dish here
from collections import Counter
t=int(input())
for x in range(t):
    inp = list(map(int,input().split()))
    r=inp[0]
    c=inp[1]
    listo=[]
    listb=set()
    pair=0
    for i in range(r):
        
        string=input()
        for j in range(len(string)):
            if(string[j]=='U'):
                listo.append([i,j,1])
            elif(string[j]=='D'):
                listo.append([i,j,2])
            elif(string[j]=='L'):
                listo.append([i,j,3])
            elif(string[j]=='R'):
                listo.append([i,j,4])
            elif(string[j]=='#'):
                listb.add((i,j))
    
                
    for y in range(max(r,c)):
        nants=Counter()
        for i in range(len(listo)):
            if(listo[i][2]!=5):
                nants[tuple(listo[i][:-1])]+=1
        for key in nants:
            pair+=(nants[key]*(nants[key]-1))//2
        
        for ant in listo:
            if(ant[2]==1):
                 ant[0]-=1
            elif(ant[2]==2):
                ant[0]+=1
            elif(ant[2]==3):
                ant[1]-=1
            elif(ant[2]==4):
                ant[1]+=1
            if(tuple(ant[:-1])) in listb:
                ant[2]=5
            elif(ant[0]<0) or ant[0]>=r:
                ant[2]=5
            elif ant[1]<0 or ant[1]>=c:
                ant[2]=5
    print(pair)
            
            
             
    
        
                
        
    


T = int(input())

while T > 0:
    R, C = input().split()
    R = int(R)
    C = int(C)
    output = [ [0] * C for i in range(R) ]
    for i in range(R):
        for j in range(C):
            output[i][j] = dict()
    matrix = [0] * R
    for i in range(R):
        matrix[i] = input()
    for i in range(R):
        for j in range(C):
            if matrix[i][j] == 'R':
                column = j + 1
                while column < C and matrix[i][column] != '#':
                    output[i][column][column-j] = output[i][column].get(column-j,0) + 1
                    column = column + 1
            elif matrix[i][j] == 'L':
                column = j - 1
                while column >= 0 and matrix[i][column] != '#':
                    output[i][column][j-column] = output[i][column].get(j-column,0) + 1
                    column = column - 1
            elif matrix[i][j] == 'U':
                row = i - 1
                while row >= 0 and matrix[row][j] != '#':
                    output[row][j][i-row] = output[row][j].get(i-row,0) + 1
                    row = row - 1
            elif matrix[i][j] == 'D':
                row = i + 1
                while row < R and matrix[row][j] != '#':
                    output[row][j][row-i] = output[row][j].get(row-i,0) + 1
                    row = row + 1
    no_of_pairs = 0
    for i in range(R):
        for j in range(C):
            for no_of_steps, count in output[i][j].items():
                if count > 1:
                    no_of_pairs = no_of_pairs + (count*(count-1)) // 2
    print(no_of_pairs)
    T = T - 1

 
import math as mt 
def countPairs(arr, n): 

	mp = dict() 
	for i in range(n): 
		if arr[i] in mp.keys(): 
			mp[arr[i]] += 1
		else: 
			mp[arr[i]] = 1
	ans = 0
	for it in mp: 
		count = mp[it] 
		ans += (count * (count - 1)) // 2
	return ans 

# cook your dish here
for _ in range(int(input())):
    (r,c)= map(int,input().split())
    has = []
    simple = []
    for i in range(r):
        lis = input()
        lis = list(lis)
        for j in range(c):
            if(lis[j]=='#'):
                has.append([i,j])
            elif(lis[j]!='-'):
                simple.append([lis[j],[i,j]])
    sum1=0
    for j in range(max(r,c)):
        he ,del1= [],[]
        flag = 0
        for i in simple:
            if(i[0]=='R' and i[1][1]+j+1<=c):
                if(has.count([i[1][0],i[1][1]+j+1])==0):
                    he.append((i[1][0],i[1][1]+j+1))
                else:
                    del1.append(i)
            elif(i[0]=='D' and i[1][0]+j+1<=r):
                if(has.count([i[1][0]+j+1,i[1][1]])==0):
                    he.append((i[1][0]+j+1,i[1][1]))
                else:
                    del1.append(i)
                    
            elif(i[0]=='L' and i[1][1]-j-1>=0):
                if(has.count([i[1][0],i[1][1]-j-1])==0):
                    he.append((i[1][0],i[1][1]-j-1))
                else:
                    del1.append(i)
                    
            elif(i[0]=='U' and (i[1][0]-j-1)>=0):
                if(has.count([i[1][0]-j-1,i[1][1]])==0):
                    he.append((i[1][0]-j-1,i[1][1]))
                else:
                   del1.append(i)
        sum1+=countPairs(he,len(he))
        for p in del1:
            simple.remove(p)
    print(sum1)

import math

def nCr(n):
    f = math.factorial
    return f(n) // f(2) // f(n-2)
# Python3 program to count of index pairs 
# with equal elements in an array. 
import math as mt 

# Return the number of pairs with 
# equal values. 
def countPairs(arr, n): 

	mp = dict() 

	# Finding frequency of each number. 
	for i in range(n): 
		if arr[i] in mp.keys(): 
			mp[arr[i]] += 1
		else: 
			mp[arr[i]] = 1
			
	# Calculating pairs of each value. 
	ans = 0
	for it in mp: 
		count = mp[it] 
		ans += (count * (count - 1)) // 2
	return ans 

# cook your dish here
for _ in range(int(input())):
    (r,c)= map(int,input().split())
    has = []
    simple = []
    for i in range(r):
        lis = input()
        lis = list(lis)
        for j in range(c):
            if(lis[j]=='#'):
                has.append([i,j])
            elif(lis[j]!='-'):
                simple.append([lis[j],[i,j]])
    sum1=0
    for j in range(max(r,c)):
        he ,del1= [],[]
        flag = 0
        for i in simple:
            if(i[0]=='R' and i[1][1]+j+1<=c):
                if(has.count([i[1][0],i[1][1]+j+1])==0):
                    he.append((i[1][0],i[1][1]+j+1))
                else:
                    del1.append(i)
            elif(i[0]=='D' and i[1][0]+j+1<=r):
                if(has.count([i[1][0]+j+1,i[1][1]])==0):
                    he.append((i[1][0]+j+1,i[1][1]))
                else:
                    del1.append(i)
                    
            elif(i[0]=='L' and i[1][1]-j-1>=0):
                if(has.count([i[1][0],i[1][1]-j-1])==0):
                    he.append((i[1][0],i[1][1]-j-1))
                else:
                    del1.append(i)
                    
            elif(i[0]=='U' and (i[1][0]-j-1)>=0):
                if(has.count([i[1][0]-j-1,i[1][1]])==0):
                    he.append((i[1][0]-j-1,i[1][1]))
                else:
                   del1.append(i)
        sum1+=countPairs(he,len(he))
        for p in del1:
            simple.remove(p)
    print(sum1)

def check_left_hor(mat, row, col, r,c, z, diff):
	if 0<=(z+diff)<c and mat[row][z+diff]=="L":

		for q in range(z+1, z+diff):
			if mat[row][q] == "#":
				return False

		return True

	return False


def check_left_ver(mat, row, col, r,c, z, diff):
	if 0<=(col+diff)<c and mat[z][col+diff]=="L":

		for q in range(col+1, col+diff):
			if mat[z][q] == "#":
				return False

		return True

	return False


def check_right_hor(mat, row, col, r,c, z, diff):
	if 0<=(z-diff)<c and mat[row][z-diff] == "R":

		for q in range(z-1, z-diff, -1):
			if mat[row][q] == "#":
				return False

		return True

	return False


def check_right_ver(mat, row, col, r,c, z, diff):
	if 0<=(col-diff)<c and mat[z][col-diff] == "R":

		for q in range(col-1, col-diff, -1):
			if mat[z][q] == "#":
				return False

		return True

	return False


def check_down_hor(mat, row, col, r,c, z, diff):
	if 0<=(row-diff)<r and mat[row-diff][z] == "D":
		
		for q in range(row-diff, row):
			if mat[q][z] == "#":
				return False

		return True

	return False


def check_down_ver(mat, row, col, r,c, z, diff):
	if 0<=(z-diff)<r and mat[z-diff][col] == "D":
		
		for q in range(z-diff, z):
			if mat[q][col] == "#":
				return False

		return True

	return False


def check_up_hor(mat, row, col, r,c, z, diff):
	# print(z, row, diff)
	if 0<=(row+diff)<r and mat[row+diff][z] == "U":
		for q in range(row+1, row+diff):
			if mat[q][z] == "#":
				return False

		return True

	return False

def check_up_ver(mat, row, col, r,c, z, diff):

	if 0<=(z+diff)<r and mat[z+diff][col] == "U":
		for q in range(z+1, z+diff):
			if mat[q][col] == "#":
				return False

		return True

	return False


t = int(input())

for i in range(t):
	r, c = map(int, input().split())

	mat = []
	count = 0

	for j in range(r):
		temp = []
		s = input()

		for a in range(c):
			temp.append(s[a])
			if s[a]!="-" and s[a]!="#":
				# print(s[a]=="-")
				count+=1

		mat.append(temp)

	# print(count, mat)
	meets = 0

	for row in range(r):

		for col in range(c):

			if mat[row][col]=="-" or mat[row][col]=="#":
				continue

			else:

				if mat[row][col] == "U":

					for z in range(row-1, -1, -1):
						if mat[z][col] == "#":
							break

						else:
							diff = row-z
							if check_left_ver(mat, row, col, r, c, z, diff):
								meets+=1

							if check_right_ver(mat, row, col, r, c, z, diff):
								meets+=1

							if check_down_ver(mat, row, col, r, c, z, diff):
								meets+=1


				if mat[row][col] == "D":

					for z in range(row+1, r):
						if mat[z][col] == "#":
							break

						else:
							# print(col-row+z, col, row, z)
							diff = z-row
							if check_left_ver(mat, row, col, r, c, z, diff):
								meets+=1

							if check_right_ver(mat, row, col, r, c, z, diff):
								meets+=1

							if check_up_ver(mat, row, col, r, c, z, diff):
								meets+=1

				if mat[row][col] == "L":

					for z in range(col-1, -1, -1):
						if mat[row][z] == "#":
							break

						else:
							diff = col-z
							# print(col-row+z, col, row, z)
							if check_down_hor(mat, row, col, r, c, z, diff):
								meets+=1

							if check_right_hor(mat, row, col, r, c, z, diff):
								meets+=1

							if check_up_hor(mat, row, col, r, c, z, diff):
								meets+=1

				if mat[row][col] == "R":

					for z in range(col+1, c):
						if mat[row][z] == "#":
							break

						else:
							# print(col-row+z, col, row, z)
							diff = z-col
							if check_down_hor(mat, row, col, r, c, z, diff):
								meets+=1

							if check_left_hor(mat, row, col, r, c, z, diff):
								meets+=1


							if check_up_hor(mat, row, col, r, c, z, diff):
								meets+=1


	print(meets//2)

for _ in range(int(input())):
    r, c = map(int, input().split())
    board = []
    for i in range(r):
        x = input()
        board.append(x)

    coll = []
    for i in range(r):
        coll.append([])
        for j in range(c):
            coll[i].append([])

    for i in range(r):
        for j in range(c):
            if board[i][j]=='-' or board[i][j]=='#':
                pass
            else:
                cnt = 1
                if board[i][j]=='D':
                    for k in range(i+1,r):
                        if board[k][j]=='#':
                            break
                        coll[k][j].append(cnt)
                        cnt+=1

                if board[i][j]=='U':
                    for k in range(i-1,-1,-1):
                        if board[k][j]=='#':
                            break
                        coll[k][j].append(cnt)
                        cnt+=1
                
                if board[i][j]=='R':
                    for k in range(j+1,c):
                        if board[i][k]=='#':
                            break
                        coll[i][k].append(cnt)
                        cnt+=1
                
                if board[i][j]=='L':
                    for k in range(j-1,-1,-1):
                        if board[i][k]=='#':
                            break
                        coll[i][k].append(cnt)
                        cnt+=1
    cnts = 0
    for i in range(r):
        for j in range(c):
            if len(coll[i][j])>1:
                sets = set(coll[i][j])
                counts = {}
                for k in sets:
                    counts[k]=0
                for k in coll[i][j]:
                    counts[k]+=1
                for k in counts.values():
                    if k>1:
                        cnts+=int(k*(k-1)//2)
    #print(counts)
    print(cnts)


# Contest Code: PRACTICE      Problem Code: ANTEATER
#
# Author: Keyur Shroff
# Date: 24 June 2019

import math
from collections import defaultdict

# --- Function to calculate nCr
def nCr(n,r):
    f = math.factorial
    return (f(n) // f(r)) // f(n-r)

# --- Main Program ---
def main() :
    t = int(input())
    for _ in range(t) :
        r, c = map(int, input().split())
        matrix = []
        for i in range(r) :
            data = list(input())
            matrix.append(data)
        
        timeHorizon = defaultdict(int)
        for i in range(r) :
            for j in range(c) :
                if (matrix[i][j] == "U") :
                    step = 1
                    for k in range(i-1, -1, -1) :
                        if (matrix[k][j] == "#") :
                            break
                        timeHorizon[(step,k,j)] += 1
                        step += 1
                elif (matrix[i][j] == "D") :
                    step = 1
                    for k in range(i+1, r, 1) :
                        if (matrix[k][j] == "#") :
                            break
                        timeHorizon[(step,k,j)] += 1
                        step += 1
                elif (matrix[i][j] == "L") :
                    step = 1
                    for k in range(j-1, -1, -1) :
                        if (matrix[i][k] == "#") :
                            break
                        timeHorizon[(step,i,k)] += 1
                        step += 1
                elif (matrix[i][j] == "R") :
                    step = 1
                    for k in range(j+1, c, 1) :
                        if (matrix[i][k] == "#") :
                            break
                        timeHorizon[(step,i,k)] += 1
                        step += 1
        
        # Count total number of pairs of ants that meet each other
        count = 0
        for key in timeHorizon :
            if (timeHorizon[key] > 1) :
                ants = timeHorizon[key]
                count += nCr(ants, 2)
        
        print(count)


def __starting_point():
    #import profile
    #profile.run('main()')
    main()
    
__starting_point()

t = int(input())
for _ in range(t):
    r, c = map(int, input().split())
    a = [list(input()) for _ in range(r)]
    ans = 0
    for i, row in enumerate(a):
        for j, x in enumerate(row):
            if x == 'R':
                for k, y in enumerate(row[j + 1:]):
                    if y == '#':
                        break
                    if k % 2 and y == 'L':
                        ans += 1
            elif x in 'UD':
                b = a[i + 1:] if x == 'D' else reversed(a[:i])
                for k, row1 in enumerate(b, 1):
                    if row1[j] == '#':
                        break
                    if k % 2 == 0 and row1[j] == 'UD'[x == 'U']:
                        ans += 1
                    m = j - k
                    if m >= 0 and row1[m] == 'R' and '#' not in row1[m + 1: j]:
                        ans += 1
                    m = j + k
                    if m < c and row1[m] == 'L' and '#' not in row1[j + 1: m]:
                        ans += 1
                a[i][j] = None
    print(ans)