# 활주로 건설 - SWEA

활주로 건설 - SWEA

def check(r):
    tmp = r[0]
    up_flag = 1
    down_flag = 0
    for i in range(1, len(r)):
        # 직진
        if r[i] == tmp:
            if down_flag:
                down_flag -= 1
            else:
                up_flag += 1
        # 오름
        elif r[i] == tmp + 1 and up_flag >= X:
            tmp += 1
            up_flag = 1
        # 내림
        elif r[i] == tmp - 1 and not down_flag:
            tmp -= 1
            down_flag = X - 1
            up_flag = 0
        else:
            return False
    # 맵 밖
    if down_flag:
        return False
    return True

T = int(input())

for test_case in range(1, T + 1):
    N, X = map(int, input().split())
    a = [list(map(int, input().split())) for _ in range(N)]
    b = [[0] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            b[j][i] = a[i][j]

    cnt = 0
    for r in a:
        cnt += check(r)
    for r in b:
        cnt += check(r)

    print("#" + str(test_case) + " " + str(cnt))