Problem:


Score : 500 points

Problem Statement

Snuke has two boards, each divided into a grid with N rows and N columns.
For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

First, choose two integers A and B ( 0 \leq A, B < N ).

Write one letter in each square on the second board.
Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board.
Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

1 \leq N \leq 300

S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Sample Input 1

2
ab
ca

Sample Output 1

2

For each pair of A and B, the second board will look as shown below:

The second board is a good board when (A,B) = (0,1) or (A,B) = (1,0), thus the answer is 2.

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

Every possible choice of A and B makes the second board good.

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

No possible choice of A and B makes the second board good.



Sample input:
2
ab
ca


Sample output:
2

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n = int(input())
s = [list(input()) for _ in range(n)]

def check(a):
    t = np.array(s[a:] + s[:a])
    t_t = t.T
    
    return (t == t_t).all()

ans = [check(a) for a in range(n)]
print(ans.count(True) * n)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
import numpy as np
N = int(input())
lisS = [list(map(ord, list(input()))) for _ in range(N)]
arS = np.array(lisS)

arExt = np.tile(arS, [2,2])[:-1,:-1]

cnt = 0
for i, j in product(range(N),range(N)):
    ar = arExt[i:i+N, j:j+N]
    cnt += ((ar - ar.T) == 0).all()

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
from sys import exit, setrecursionlimit
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

def read():
  return int(input())

def reads():
  return [int(x) for x in input().split()]

p = 10**9 + 7
M = 1 << 64

N = read()
S = []

for _ in range(N):
  S.append([ord(c) for c in input()])

St = [[S[j][i] for j in range(N)] for i in range(N)]

rhS = [[0] * (N+1) for i in range(N)]
for i in range(N):
  for j in range(N):
    rhS[i][j+1] = (rhS[i][j] * p + S[i][j]) % M

rhSt = [[0] * (N+1) for i in range(N)]
for i in range(N):
  for j in range(N):
    rhSt[i][j+1] = (rhSt[i][j] * p + St[i][j]) % M

pp = [1] * (N+11)
for k in range(N+10):
  pp[k+1] = (pp[k] * p) % M

def rotate(rhRow, k):
  return (rhRow[k] + (rhRow[N] - rhRow[k] * pp[N-k]) * pp[k]) & (M-1)

ans = 0
for A in range(N):
  for B in range(N):
    if all(rotate(rhS[(i + A) % N], B) == rotate(rhSt[(i + B) % N], A) for i in range(N)):
      ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
exec("def nWord(): nWord.cache = raw_input() if not hasattr(nWord, 'cache') or nWord.cache=='' else nWord.cache ; pos = nWord.cache.find(nWord.sep) ; ret, nWord.cache = (nWord.cache, '') if pos==-1 else (nWord.cache[:pos], nWord.cache[pos+1:].lstrip(nWord.sep)) ; return ret") ; exec("nWord.sep = ' '") ; exec("def ___nLine2(): ret, nWord.cache = (raw_input(), nWord.cache if hasattr(nWord, 'cache') else '') if not hasattr(nWord, 'cache') or nWord.cache=='' else (nWord.cache, '') ; return ret") ; exec('def nInt(): return int(nWord())') ; exec('def nFloat(): return float(nWord())') ; exec("def ___nAuto2():\n ret = nWord()\n try: return int(ret)\n except: pass\n try: return float(ret)\n except: return ret") ; exec("def nAuto(n=None): return ___nAuto2() if n is None else [___nAuto2() for i in range(n)]") ; exec("def nLine(n=None): return ___nLine2() if n is None else [___nLine2() for i in range(n)]")

N = nAuto()
S = nAuto(N)

D = {}
for  i in range(N):
    for j in range(N):
        c = S[i][j]
        if c in D:
            D[c] += 1
        else:
            D[c] = 1

max_c = 'a'
max_count = 0
for c in D:
    if max_count < D[c]:
        max_count = D[c]
        max_c = c

L = []
for  i in range(N):
    for j in range(N):
        c = S[i][j]
        if c!=max_c:
            L.append((i, j, c))

def check(A, B):
    for i2, j2, c in L:
        i = (i2-A+N) % N
        j = (j2-B+N) % N
        if c!=S[(A+j) % N][(B+i) % N]:
            return 0
    return 1

count = 0
for A in range(N):
    for B in range(N):
        count += check(A, B)
print count

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
m = [input() for _ in range(N)]

ans = 0
for z in range(N): #ずらし
  brk = False
  for y in range(N):
    for x in range(y+1, N):
      if m[y][x] != m[x][y]:
        brk = True
        break
    if brk:
      break
  else:
    ans += N
  m = [l[-1]+l[:-1] for l in m]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
import numpy as np
N = int(input())
lisS = [list(input()) for _ in range(N)]
arS = np.array(lisS)
arExt = np.tile(arS, [2,2])[:-1,:-1]

cnt = 0
for i, j in product(range(N),range(N)):
    ar = arExt[i:i+N, j:j+N]
    cnt += (ar == ar.T).all()

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
import numpy as np
N = int(input())
alphabets = list('abcdefghijklmnopqrstuvwxyz')
A = np.zeros((N, N))
for i in range(N):
    for j, c in enumerate(input()):
        A[i,j] = alphabets.index(c)

B = np.concatenate([A, A], axis=0)
B = np.concatenate([B, B], axis=1)
cnt = 0
for i in range(N):
    for j in range(N):
        C = B[i:i+N, j:j+N]
        if (C==C.T).all():
            cnt += 1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
# B

# N = int(input())
# A = list(map(int, input().split()))

N = int(input())
S = []
for _ in range(N):
    S.append(list(input()))


def is_good(S):
    T = []
    for j in range(N):
        ls = []
        for i in range(N):
            ls.append(S[i][j])
        T.append(ls)

    if T == S:
        return True
    else:
        return False


ans = 0
for a in range(N):
    T = []
    for i in range(N):
        T.append(S[(i+a) % N])
    if is_good(T):
        ans += N

print(ans)

Submission status: Time Limit Exceeded

Solution code:

import numpy as np

N = int(input())
rows = []
for i in range(N):
    rows.append([c for c in input()])
c_mat = np.array(rows)

ans = 0
for A in range(N):
    for B in range(N):
        rows_swap = [(i + A) % N for i in range(N)]
        cols_swap = [(i + B) % N for i in range(N)]
        c_mat2 = c_mat[rows_swap, :]
        c_mat2 = c_mat2[:, cols_swap]
        if np.all(c_mat2 == c_mat2.T):
            ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
A = []
for _ in range(n):
    A.append(input())

result = 0


def check(A, k, l, n):
    for i in range(n):
        for j in range(n-i):
            if A[(i+k) % n][(j+l) % n] != A[(j+k) % n][(i+l) % n]:
                return False
    return True


for k in range(n):
    for l in range(n):
        if check(A, k, l, n):
            result += 1


print(result)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = [input() for i in range(n)]
for i in range(n): s[i] += s[i]
ans = 0
for i in range(n):
	s2 = []
	for j in s: s2.append(j[i:i+n])
	s2 += s2
	for k in range(n):
		flag = True
		for k2 in range(k,n+k):
			if any(s2[k2][k3]!=s2[k3+k][k2-k] for k3 in range(n)):
				flag = False
				break
		if flag: ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

n=int(input())
S=[]
for i in range(n):
    S.append(input())

a=0

for i in range(n):
    flag=1
    for j in range(n):
        for k in range(j):
            if S[(n+j-i)%n][k] != S[(n+k-i)%n][j]:
                flag=0
                break
    if flag == 1:
        a = a+1

print(a*n)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

n=int(input())
S=[]
for i in range(n):
    S.append(input())

a=0

for i in range(n):
    S=[S[-1]]+S[:-1]
#    print(S)
    flag=1
    for j in range(n):
        for k in range(j):
            if S[j][k] != S[k][j]:
                flag=0
                break
    if flag == 1:
        a = a+1

print(a*n)

Submission status: Time Limit Exceeded

Solution code:
def process():
    try:
        n = int(raw_input().strip())
    except ValueError:
        return True
    except EOFError:
        return False
    a = [raw_input().strip() for i in xrange(n)]
    foo = 0
    x = 0
    for y in xrange(n):
        sym = True
        for d in xrange(n):
            for k in xrange(1, n):
                if a[(x+d)%n][(y+d+k)%n]!=a[(x+d+k)%n][(y+d)%n]:
                    sym = False
                    break
            if not sym:
                break
        if sym:
            foo += 1
    print foo * n
    return True

def main():
    while True:
        if not process():
            break
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

N = int(input())
S = []

for _ in range(N):
    S.append([x for x in input()])

def verify(A):
    for a in range(N):
        for b in range(a + 1, N):
            if (S[(a + A) % N][b] != S[(b + A) % N][a]):
                return False
    return True

count = 0
for A in range(N):
    if verify(A):
        count += N

print(count)

Submission status: Accepted

Solution code:
import numpy as np
n = int(input())
S = [list(input()) for _ in range(n)]

ss = np.array(S + S)

ans = 0
for i in range(n):
    a = ss[i:i+n]
    if np.array_equal(a, a.T):
      ans += 1
print(ans * n)

Submission status: Accepted

Solution code:
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし


N = I()
S = [LS2() for _ in range(N)]

# Aj-Ai == Bj-Bi のとき、
# (Ai,Bi) を選んだときの盤面が'よい' ⇔ (Aj,Bj) を選んだときの盤面が'よい'

ans = 0
for a in range(N):
    X = [S[i] for i in range(a,N)] + [S[i] for i in range(a)]
    for i in range(N-1):
        for j in range(i+1,N):
            if X[i][j] != X[j][i]:
                break
        else:
            continue
        break
    else:
        ans += 1

print(ans*N)

Submission status: Accepted

Solution code:
N = int(input())
S = []
for i in range(N):
  temp = str(input()); temp = list(temp)
  S.append(temp)
ans = 0
for alpha in range(-N+1,N): #-N+1 ~ N-1
  #print(alpha)
  Flag = True
  for i in range(N):
    if not Flag:
      break
    for j in range(N):
      p = (j-alpha+N)%N
      q = (i+alpha)%N
      #print(alpha,S[i][j],p,q,S[p][q])
      if S[i][j] != S[p][q]:
        Flag = False
        break
  if Flag:
    ans += N - abs(alpha)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
def rotate(l, n):
    return l[-n:] + l[:-n]
s=[list(input())for i in range(n)]
ans=0;
for _ in range(n):
  for i in range(n):
    s[i]=rotate(s[i],1)
  f=1
  for i in range(n):
    for j in range(i+1,n):
      f &= s[i][j]==s[j][i]
  ans+=f
print(ans*n)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし


N = I()
S = [LS2() for _ in range(N)]
ans = 0
for a in range(N):
    X = [S[i] for i in range(a,N)] + [S[i] for i in range(a)]
    for i in range(N-1):
        for j in range(i+1,N):
            if X[i][j] != X[j][i]:
                break
        else:
            continue
        break
    else:
        ans += 1

print(ans*N)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

# N <= 300 O(n ** 3)まで
# 何通り dp or combo
N = getN()
# 1つ目の譜面
B = []
for i in range(N):
    q = list(input())
    B.append(q * 2)
B += B
# 2つ目にはなにも書かれてない
# 2つ目の盤面に縦にi、横にjずらして数字を記入する

# 対角線に対して線対称なものの数を求める
# 整数a, bの選び方が何通りあるか

def judge(a, b):
    """
    res = [[''] * N for i in range(N)]
    # 盤面１のB[i][j]を盤面2に書き込む
    for i in range(N):
        for j in range(N):
            res[(i + a) % N][(j + b) % N] = B[i][j]
    """

    for i in range(N):
        for j in range(N):
            if B[i + a][j + b] != B[j + a][i + b]:
                return 0
        else:
            continue
        break
    else:
        return 1

# 全てのa, bについて調べるなら１つの(a, b)についてO(N)で求める必要がある
# 判定する際、節約出来ないか？

# N * N のゾーンをずらしていく
# a [b  a] b
# c [a  c] a
# a  b  a  b
# c  a  c  a 対称軸がずれる 軸は2N - 1本ある
# 良い盤面になる条件

# 斜めにずらしていくことで前の結果を利用できる
# 1本の軸について判定した時、1つの盤面が良い盤面なら他全ても良い盤面
# 軸に刺さっている盤面の数を求めればいい

# 軸は2N - 1本ある
# 縦に対角線をずらす
ans = 0
for i in range(N):
    # 軸(0, i)にはN - i本の盤面が連なっている
    # 連なっている全ての盤面は全てTrueか全てFalse
    ans += (N - i) * judge(i, 0)

# 横に対角線をずらす
for i in range(1, N):
    ans += (N - i) * judge(0, i)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [list(input()) for _ in range(N)]

ans = 0
for k in range(N):
  D = [[0] * N for i in range(N)]
  for i in range(N):
    for j in range(N):
      D[i][j] = S[i][(j + k) % N]
  for i in range(N):
    for j in range(N):
      if D[i][j] != D[j][i]:
        break
    else:
      continue
    break
  else:
    ans += 1

print(ans * N)

Submission status: Accepted

Solution code:
N = int(input())
S = [list(input()) for i in range(N)]
ans = 0
for n in range(N):
    flag = True
    for i in range(N):
        for j in range(i, N):
            if S[i][j] == S[j][i]:
                continue
            flag = False
            break
        if not flag:
            break
    if flag:
        ans += N
    for i in range(N):
        S[i] = [S[i][-1-n]] + S[i]
print(ans)

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def main2():
	n = int(input())
	#b , c = tin()
	#s = input()	
	mt=[input() for _ in range(n)]
	
	tt=[]
	for i in range(n):
		l=[]
		for s in mt:
			l.append(s[i])
		tt.append(''.join(l+l))
	pa(tt)
	ret = 0
	for ai in range(n):
		for s,t in zip(mt, tt):
			pa((s, t[ai:ai+n]))
			if t[ai:ai+n] != s:
				break
		else:
			ret += n
	return ret
	
def is_s(a,mt):
	pass
	#pa(a)
	n=len(mt)
	for i in range(n):
		for j in range(n):
			#pa((mt[i+a][j], mt[j][i+a]))
			if mt[(i+a)%n][j] != mt[(j+a)%n][i]:
				return False
	return True
	
def main():
	n = int(input())
	#b , c = tin()
	#s = input()	
	mt=[list(input()) for _ in range(n)]
	ret = 0
	for i in range(n):
		if is_s(i, mt):
			ret += n
	return ret
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


def main():
    N = int(input())
    S = [input().strip() for _ in range(N)]
    print(sum(N if all(S[(i - a) % N][j] == S[(j - a) % N][i] for i in range(N) for j in range(N)) else 0 for a in range(N)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


def main():
    N = int(input())
    S = [input().strip() for _ in range(N)]
    res = 0
    for a in range(N):
        f = True
        for i in range(N):
            for j in range(N):
                if S[(i - a) % N][j] != S[(j - a) % N][i]:
                    f = False
        if f:
            res += N
    print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


def main():
    N = int(input())
    S = [input().strip() for _ in range(N)]
    res = 0
    for a in range(N):
        f = True
        for i in range(N):
            for j in range(N):
                if S[(i - a) % N][j] != S[(j - a) % N][i]:
                    f = False
                    break
            if not f:
                break
        if f:
            res += N
    print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
s = [list(input()) for i in range(n)]
ans = 0
for a in range(n):
    check = True
    for x in range(n):
        for y in range(x):
            if s[(x+a)%n][y] != s[(y+a)%n][x]:
                check = False
                break
        if check == False:
            break
    if check:
        ans += n-a
    if a == 0:
        continue
    check = True
    for x in range(n):
        for y in range(x):
            if s[x][(y+a)%n] != s[y][(x+a)%n]:
                check = False
                break
        if check == False:
            break
    if check:
        ans += n-a
print(ans)

Submission status: Accepted

Solution code:
#import sys
#input = sys.stdin.readline

def chr2ord(c):
  return ord(c) - ord('a')

N = int(input())
S = []
for i in range(N):
  wk = list(input())
  S.append(wk)

ANS = 0
# A=0として、0<=B<Nをためす。
# こたえはN倍。
for b in range(N):
  cnt = 0
  B = [['X' for _ in range(N)] for _ in range(N)]
  for i in range(N):
    for j in range(N):
      B[i][j] = S[i][(j+b)%N]
  #print(B)
  for i in range(N):
    for j in range(N):
      if B[i][j] == B[j][i]:
        cnt += 1
  
  if cnt == N*N:
    ANS += N
print(ANS)

Submission status: Accepted

Solution code:
"""
不変なもの
- 移動した行/列内の順番
○ AとBの差によって、線対称(対角線上)のものが決まる
"""
n = int(input())
fs = []
for i in range(n):
    rs = list(input())
    fs.append(rs)
cnt = 0
for a in range(n):
    flg = True
    tmp = []
    for r in fs:
        r_ = r[a:] + r[:a]
        tmp.append(r_)
    for i in range(n):
        for j in range(n):
            flg &= tmp[i][j] == tmp[j][i]
    
    cnt += flg
print(cnt*n)

Submission status: Accepted

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq

n = ni()
S =[]
for i in range(n):
    S.append(input())
def isok(a,b):
    for j in range(n):
        for i in range(j+1,n):
            if not S[(j+b)%n][(i+a)%n] == S[(i+b)%n][(j+a)%n]:
                return False
    return True

ans = 0
if isok(0,0):
    ans +=n
for a in range(1,n):
    if isok(a,0):
        ans+=n-a
    if isok(0,a):
        ans+=n-a
    #print("a",a,ans)
print(ans)

def solve2():
    ret=0
    for a in range(n):
        for b in range(n):
            if isok(a,b):
                ret+=1
                print(a,b)
    print(ret)
#solve2()

Submission status: Accepted

Solution code:
n=int(input())
s=[input() for _ in range(n)]
ans=0
for k in range(n):
  cnt=0
  for i in range(n): 
    l=(i+k)%n
    for j in range(n):
      cnt+=s[i][j]==s[(i+j-l)%n][l]
  if cnt==n**2:ans+=n
print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil,pi,factorial
    from operator import itemgetter
    def I(): return int(input())
    def MI(): return map(int, input().split())
    def LI(): return list(map(int, input().split()))
    def LI2(): return [int(input()) for i in range(n)]
    def MXI(): return [[LI()]for i in range(n)]
    def SI(): return input().rstrip()
    def printns(x): print('\n'.join(x))
    def printni(x): print('\n'.join(list(map(str,x))))
    inf = 10**17
    mod = 10**9 + 7
#main code here!
    n=I()
    S=[SI() for i in range(n)]
    ans=0
    if n==1:
        print(1)
        sys.exit()
    st=n*(n-1)//2
    for b in range(n):
        count=0
        for i in range(n-1):
            for j in range(i+1,n):
                #print(b,i,j)
                #print(i,(j+b)%n,j,(i+b)%n)
                if S[i][(j+b)%n]==S[j][(i+b)%n]:
                    count+=1
            if count==st:
                ans+=n
    print(ans)
        
        
                





if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import math
import copy
import random
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    # example 2x + y = 3, x + 3y = 4
    # A = [[2,1], [1,3]])
    # Y = [[3],[4]] または [3,4]
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    # [1.0, 1.0]
    return X.flatten().tolist()[0]

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        # self.init_cost()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        # for i in range(1, self.h+1):
        #     for j in range(1, self.w+1):
        #         cx, cy = j, i
        #         for dx, dy in move_eight:
        #             nx, ny = dx + cx, dy + cy

def solve():
    n = getN()
    g = []
    for i in range(n):
        g.append(getS())


    ans = 0
    for zu in range(n):
        fl = True
        for i in range(n):
            for j in range(n):
                if g[i][(j+zu) % n] != g[j][(i+zu) % n]:
                    fl = False
                    break
            if not fl:
                break
        if fl:
            ans += n

    print(ans)



def main():
    n = getN()
    for _ in range(n):
        s = "".join([random.choice(["F", "T"]) for i in range(20)])
        print(s)
        solve(s, 1, 0)

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
N=int(input())
S=["" for j in range(N)]
for i in range(N):
    S[i]=input()

ans=0
for i in range(0,N):
    ans+=N*int(all(S[(k+i)%N][j]==S[(j+i)%N][k] for j in range(N) for k in range(N)))

print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    def calc(x):
        for row in range(n):
            for col in range(n):
                if s[(row + x) % n][col] != s[(col + x) % n][row]:
                    return 0
        return n

    n = int(readline())
    s = [input() for _ in range(n)]

    ans = 0

    for i in range(n):
        ans += calc(i)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

N = int(sys.stdin.readline())
grid = []
for _ in range(N):
    grid.append(list(sys.stdin.readline().strip()*2))
for i in range(N):
    grid.append(grid[i])

ans = 0
for a in range(N):
    flag = False
    for i in range(N):
        for j in range(N):
            # print(i+a, j)
            if grid[i+a][j] != grid[j+a][i]:
                flag = True 
                break
        if flag:
            break
    else:
        ans += 1

print(ans * N)

Submission status: Accepted

Solution code:
I,R=input,range
n=int(I())
s=[I()for i in R(n)]
a=0
for i in R(n):
 if all(s[(i+j)%n][k]==s[(i+k)%n][j]for j in R(n)for k in R(j+1,n)):a+=n
print(a)

Submission status: Accepted

Solution code:
import numpy as np
n = int(input())
S = [list(input()) for _ in range(n)]

ss = [s + s for s in S]
ss = np.array(ss + ss)

ans = 0
for i in range(n):
    a = ss[i:i + n, :n]
    if np.array_equal(a, a.T):
      ans += 1
print(ans * n)

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for i in range(n)]
ans = 0
for i in range(n):
    flag = True
    for x in range(n):
        for y in range(n):
            if s[(x-i)%n][y] != s[(y-i)%n][x]:
                flag = False
    if flag:
        ans += 1
print(ans*n)

Submission status: Accepted

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

import numpy as np

n = int(input())
s = [list(input())*2 for _ in range(n)]
s = s * 2
s = np.array(s)
ret = 0
for a in range(n):
    si = s[a:a+n, :n]
    if (si == si.T).all():
        ret += 1
print(ret*n)

Submission status: Accepted

Solution code:
N = int(input())
S = [list(input()) for _ in range(N)]
#N = 300
#S = [["a"]*N for _ in range(N)]
ans = 0

for A in range(N):
    if all([S[(i+A)%N][j] == S[(j+A)%N][i] for i in range(N) for j in range(i+1, N)]):
        ans += N
print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())
    grid = [list(input().rstrip()) for _ in range(n)]

    for i in range(1, n):
        target = [grid[0][(i + j) % n] for j in range(n)]
        if grid[i] != target:
            break
    else:
        print(n ** 2)
        exit()

    res = 0
    for a in range(n):
        grid2 = [[""] * n for _ in range(n)]
        for i in range(n):
            for j in range(n):
                grid2[i][j] = grid[(i + a) % n][j]
        for i in range(n):
            for j in range(n):
                if grid2[i][j] != grid2[j][i]:
                    break
            else:
                continue
            break
        else:
            res += 1
    print(res * n)


if __name__ == '__main__':
    resolve()