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: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
  
N = I()
data = SLs(N)

data = [i*2 for i in data] * 2
ans = 0
for i in range(N):
  oy,ox = 0,i
  flag = 1
  for j in range(N):
    for k in range(N):
      if data[oy+j][ox+k] != data[oy+k][ox+j]:
        flag = 0
        break
    if not flag:
      break
  if flag:
    ans += 1
print(ans*N)

Submission status: Accepted

Solution code:
n = int(input())
fs = []
for _ in range(n):
    r = list(input())
    r = [ord(s) - ord("a") for s in r]    
    fs.append(r)
sym = [[0]*n for i in range(n)]
cnt = 0
# di,dj とdi+1,dj+1が同値
# dj側は0で固定して良い
for di in range(n):
    for i in range(n):
        for j in range(n):
            sym[(i+di)%n][j] = fs[i][j]
    flg = True
    for i in range(n):
        for j in range(i+1,n):
            if sym[i][j] != sym[j][i]:
                flg = False
                break
    if flg:
        cnt += n
print(cnt)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
s = [None]*n
for i in range(n):
    s[i] = input()
    
ans = n * sum(all(all(s[(i+j)%n][(j+k)%n]==s[(i+j+k)%n][j] for k in range(n)) for j in range(n)) for i in range(n))
print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
s = [None]*n
for i in range(n):
    s[i] = input()
    
def sub(i):
#     res = True
#     for j in range(n):
#         if not all(s[(i+j)%n][(j+k)%n]==s[(i+j+k)%n][j] for k in range(n)):
#             res = False
#             break
    res = all(all(s[(i+j)%n][(j+k)%n]==s[(i+j+k)%n][j] for k in range(n)) for j in range(n))
    return res
ans = 0
for i in range(n):
    if sub(i):
        ans += n
print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
s = [None]*n
for i in range(n):
    s[i] = input()
    
def sub(i):
    res = True
    for j in range(n):
        if not all(s[(i+j)%n][(j+k)%n]==s[(i+j+k)%n][j] for k in range(n)):
            res = False
            break
    return res
ans = 0
for i in range(n):
    if sub(i):
        ans += n
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import numpy as np

def gen_check(N: int, S: "List[str]"):
    tmp = [tuple(s)+tuple(s) for s in S]
    S = np.array(tmp+tmp)
    def check(a, b):
        s = S[a:a+N,b:b+N]
        return np.array_equal(s, s.T)
    return check

def solve(N: int, S: "List[str]"):
    ans = 0
    check = gen_check(N, S)
    for a in range(N):
        if check(a, 0):
            ans += N
    return ans

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    S = [next(tokens) for _ in range(N)]  # type: "List[str]"
    print(solve(N, S))

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Accepted

Solution code:
n=int(input())
s=[list(input()) for _ in range(n)]
import numpy as np
ss=[si+si for si 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:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

import numpy as np
def main():
    N = int(input())
    grid = np.array([list(input()) for _ in range(N)],'S1')
    
    ans = 0
    for i in range(N):
        X = np.vstack((grid[i:,:],grid[:i,:]))
        if np.all(X == X.T):
            ans += N
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

def main():
    N = int(input())
    grid = [input() for _ in range(N)]

    ans = 0
    for i in range(N):
        flag = True
        for j in range(N):
            for k in range(N):
                if j == k:
                    continue
                if grid[j][(k + i)%N] != grid[k][(j + i)%N]:
                    flag = False
                    break
        if flag:
            ans += N
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np
import sys
input = sys.stdin.readline
def main():
    n = int(input())
    A = np.array([list(input().rstrip()) for _ in range(n)], dtype='str')
    ans = 0
    for i in range(n):
        B = np.block([A[:, i:], A[:, :i]])
        if (B == B.T).all():
            ans += n
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np
def main():
    n = int(input())
    A = np.array([list(map(lambda x: '{}'.format(x), input())) for _ in range(n)], dtype='U')
    ans = 0
    for i in range(n):
        B = np.block([A[:, i:], A[:, :i]])
        if np.array_equal(B, B.T):
            ans += n
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#AGC023-B Find Symmetries
"""
各300*300の場所について、シフト数は300*300通り存在する。
実は、縦方向へのシフトをA,横方向へのシフトをBとした時、
A=Bとなるような状態では結果は等しくなる。
よって、縦方向もしくは横方向どちらかのみ動かせばよく、その時の判定にはN^2かかるので、
合計O(N^3)で求まった。
答えは、片方のシフトで求まった個数*nとなる(もう片方のシフトもn通りあるので)
"""
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
n = int(readline())
lst1 = []
for i in range(n):
    lst1.append(readline().rstrip().decode('utf-8'))

def judge(k):
    for i in range(n):
        for j in range(n):
            if lst1[(i+k)%n][j] != lst1[(j+k)%n][i]:
                return 0
    
    return 1

ans = 0
for i in range(n):
    ans += judge(i)

print(ans*n)

Submission status: Accepted

Solution code:
n = int(input())
s = [ input() * 2 for _ in range(n)]

ans = 0
for k in range(n):
    check = 1
    for i in range(n-1):
        for j in range(i+1,n):
            if(s[i][j+k] != s[j][i+k]):
                check = 0
                break
        if(check==0):
            break
    ans += check * n

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
T = ["".join(s) for s in zip(*S)]

ans = 0
for _ in range(N):
    ans += (S == T)
    S = [s[-1] + s[:-1] for s in S]
    T = T[-1:] + T[:-1]

print(N * ans)

Submission status: Accepted

Solution code:
import sys
def main():
    input = sys.stdin.readline
    N = int(input())
    S = [list(input().rstrip()) for _ in range(N)]
    ans = 0
    for B in range(N):
        for i in range(N):
            ni = (i + B) % N
            for j in range(N):
                nj = (j + B) % N
                if S[i][nj] != S[j][ni]:
                    break
            else:
                continue
            break
        else:
            ans += 1
    print(ans * N)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

def AddV2(v,w):
    return [v[0]+w[0],v[1]+w[1]]

dir4 = [[1,0],[0,1],[-1,0],[0,-1]]


def clamp(x,y,z):
    return max(y,min(z,x))

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
            
#
def Zaatsu(a):
    a.sort()
    now = a[0][0]
    od = 0
    for i in range(n):
        if(now==a[i][0]):
            a[i][0]=od
        else:
            now = a[i][0]
            od+=1
            a[i][0] = od
    
    a.sort(key = lambda x : x[1])
    return a

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)


'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''

def rl(x):
    return range(len(x))

# a = list(map(int, input().split()))

#################################################
#################################################
#################################################
#################################################

#31-

n = int(input())

s = []

for i in range(n):
    s.append( input() )
ans = 0
for i in range(n):
    ok = 1
    for j in range(n):
        for k in range(n):
            #print(i,x,y,s[x][y],s[y][x])
            if(s[-i+j][k]!=s[-i+k][j]):
                ok=0
    if(ok==1):
        ans+=1
print(ans*n)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N = int(rl())
    S = [rl().rstrip() for _ in range(N)]
    
    ans = 0
    for b in range(N):
        flg = True
        for i in range(N):
            ii = (i + b) % N
            for j in range(N):
                jj = (j + b) % N
                if S[i][jj] != S[j][ii]:
                    flg = False
                    break
            if not flg:
                break
        ans += flg
    ans *= N
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N = int(rl())
    S = [rl().rstrip() for _ in range(N)]
    
    ans = 0
    for b in range(N):
        flg = True
        for i in range(N):
            for j in range(N):
                ii = (i + b) % N
                jj = (j + b) % N
                if S[i][jj] != S[j][ii]:
                    flg = False
                    break
            if not flg:
                break
        ans += flg
    ans *= N
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import numpy as np

N = int(input())
S = np.array([list(input()) for i in range(N)])

ans = 0
for i in range(N):
  S_new = np.c_[S[:, i:], S[:, :i]]
  if (S_new == S_new.T).all():
    ans += N

print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
import numpy as np
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
S = [list(input()) for _ in range(N)]
for i in range(N):
	for j in range(N):
		S[i][j] = ord(S[i][j])
S = np.array(S, dtype=np.int32)

def is_symmetric(a):
    return np.array_equal(a, a.T)

ans = 0

for i in range(N):
	S_roll = np.roll(S, i, axis=0)
	if is_symmetric(S_roll): ans += 1

print(ans*N)

Submission status: Accepted

Solution code:
N=int(input())
S=[input() for i in range(N)]
a=0
for i in range(N):
    for j in range(N-1):
        for k in range(j+1,N):
            if S[(j+i)%N][k]!=S[(k+i)%N][j%N]:
                break
        else:
            continue
        break
    else:
        a+=1
print(a*N)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    grid = []
    for i in range(N):
        grid.append(list(input()))
    res = 0
    for a in range(1,2*N):
        
        flag = True
        for i in range(N):
            for j in range(N):
                if grid[i][j] != grid[j][i]:
                    flag = False
        # print(grid)
        grid.insert(0,grid[-1])
        del grid[-1]
        if not flag:
            continue
        res+=N-abs(a-N)
    print(res)
main()

Submission status: Accepted

Solution code:
import numpy as p
n = int(input())
a = p.array([list(input()) for i in range(n)])
s = 0
for i in range(n):
  c = p.roll(a,i,0)
  if p.array_equal(c,c.T):
    s += 1
print(s*n)

Submission status: Accepted

Solution code:
import numpy as np
import sys
input = sys.stdin.readline
n = int(input())
a = np.array([list(input().rstrip()) for i in range(n)])
ans = 0
for i in range(n):
  c = np.roll(a,i,axis=0)
  if np.array_equal(c,c.T):
    ans += 1
print(ans*n)

Submission status: Accepted

Solution code:
import numpy as np

n = int(input())
s = np.array([list(ord(e) - ord("a") for e in input()) for _ in range(n)], np.int8)

ans = 0
for _ in range(n):
    s = np.roll(s, 1, axis=1)
    if (s == s.T).all():
        ans += n

print(ans)

Submission status: Accepted

Solution code:
import numpy as np

n = int(input())
s = np.array([list(ord(e) - ord("a") for e in input()) for _ in range(n)], np.int8)
s = np.hstack((s, s))

ans = 0
for b in range(n):
    t = s[:, b:b+n]
    if (t == t.T).all():
        ans += 1

ans *= n
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for i in range(n)]
t = []
for i in range(n):
    u = []
    for j in range(n):
        u.append(s[j][i])
    t.append("".join(u))

ans = 0
for i in range(n):
    a = []
    b = []
    for k in range(n):
        a.append(s[k][n-i:])
        a.append(s[k][:n-i])
        b.append(t[(k-i)%n])
    if "".join(a) == "".join(b):
        ans += 1

print(ans*n)

Submission status: Accepted

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

def main():
  n = int(input())
  board = []
  for _ in range(n):
    board.append(input().strip())
    
  def t(mat):
    return ["".join(s) for s in zip(*mat)]
  tboard = t(board)
  
  def judge(board, tboard):
    if all([x==y for x, y in zip(board, tboard)]):
      return True
    return False
  
  cnt = 0 
  for i in range(n):
    if judge(board[i:] + board[:i], t(board[i:] + board[:i])):
      cnt += 1
  print(n * cnt)
  
if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = float(10 ** 5)
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007

n = I()
s = SR(n)
ans = 0
for i in range(n):
    flg = True
    for j in range(n):
        for k in range(n):
            if s[(j + i) % n][k] != s[(k + i) % n][j]:
                flg = False
                break
        if not flg:
            break
    else:
        ans += n

print(ans)

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):
    flag=True
    for j in range(0,N):
        for k in range(0,N):
            flag=flag&(S[(k+i)%N][j]==S[(j+i)%N][k])
    ans+=N*int(flag)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
sl = []

for _ in range(n):
    s = list(input())
    sl.append(s)

ans = 0
for i in range(n):
    flag = True
    for j in range(n):
        for k in range(n):
            if j != k:
                if sl[j][(k+i)%n] != sl[k][(j+i)%n]:
                    flag = False
    if flag:
        ans += n

print(ans)

Submission status: Accepted

Solution code:
#editorial参照
#a,bとa+1,b+1での成立は同値でa=0のみ数える
n=int(input())
s=[input() for _ in range(n)]
ans=0
for i in range(n):
    s2=[s[b][i:]+s[b][:i] for b in range(n)]
    flag=True
    for b in range(n):
        for c in range(n):
            if s2[b][c]!=s2[c][b]:
                flag=False
                break
    ans+=flag

print(ans*n)

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans

"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def rotate(ro,a,n):

    for i in range(n):
        for j in range(n):
            if ro[i][(j+a)%n] != ro[j][(i+a)%n]:
                break
        else:
            continue
        break
    else:
        return 1

    return 0

ans = 0

n = onem()

dp = [list(input())[:-1] for i in range(n)]

for i in range(n):

    po = rotate(dp,i,n)

    ans += po * n

print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n=int(input())
S=[list(input()) for i in range(n)]
def check(s,b):
    for i in range(n-1):
        for j in range(i+1,n):
            if s[i][(j-b)%n]!=s[j][(i-b)%n]:
                return False
    return True
ans=0
for i in range(n):
    if check(S,i):ans+=n
print(ans)

Submission status: Accepted

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

ans=0
for a in range(N):
    new_grid=[]
    new_grid.extend(grid[a:])
    new_grid.extend(grid[:a])

    flag=True
    for i in range(N):
        for j in range(N):
            if new_grid[i][j]==new_grid[j][i]:
                continue
            else:
                flag=False
                break
    if flag:
        ans+=1
print(ans*N)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10

#solve
def solve():
    n = II()
    s = []
    for i in range(n):
        t = S()
        t += t
        s.append(t)
    ans = 0
    for i in range(n):
        f = True
        for j in range(i, i + n):
            for k in range(n):
                if s[k][j] != s[j - i][k + i]:
                    f = False
                    
        if f:
            ans += n
    print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
n = int(input())
s = [list(input()) for i in range(n)]
s += s

def ok(array):
    for i in range(1,n):
        for j in range(i):
            if array[i][j] != array[j][i]:
                return False
    return True
ans = 0
for i in range(n):
    if ok(s[i:i+n]):
        ans += n
print(ans)

Submission status: Accepted

Solution code:
# 解説AC
import numpy as np

def is_symmetric(a):
    """
    対象行列判定 O(N * N)
    """
    return np.array_equal(a, a.T)

def main():
    N = int(input())
    S = [[ord(s) - ord("a") for s in list(input())] for _ in range(N)]

    S = np.array(S)

    ans = 0
    for B in range(N):
        if is_symmetric(np.roll(S, B, axis=1)):
            ans += N

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7

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

ans=0
for i in range(n):
    flag=0
    for j in range(n):
        for k in range(n):
            # print(s[(i+j)%n][k],s[(i+k)%n][j])
            if s[(i+j)%n][k]!=s[(i+k)%n][j]:
                flag=1
    # print(flag)
    if flag==0:
        ans+=n
    # print()
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
l = []
for i in range(n):
    l.append(list(input()))

def check():
    for i in range(n):
        for j in range(n):
            if i==j:
                continue
            if l[i][j] != l[j][i]:
                return False
    return True

def sft(old):
    newl=[]
    for lis in old:
        last = lis.pop()
        lis.insert(0,last)
        newl.append(lis)
    return newl

cnt=0
for i in range(n):
    if check():
        cnt+=1
    l=sft(l)
print(cnt*n)

Submission status: Accepted

Solution code:
N=int(input())
X=range(N)
S=[input()for _ in X]
print(sum(all(S[(i+k)%N][j]==S[(j+k)%N][i]for i in X for j in X)for k in X)*N)

Submission status: Accepted

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

N = int(input())
S = [list(input().rstrip()) for _ in range(N)]
row = [[0] * 26 for _ in range(N)]
col = [[0] * 26 for _ in range(N)]
for i in range(N):
    for j in range(N):
        c = ord(S[i][j]) - ord('a')
        row[i][c] += 1
        col[j][c] += 1
ans = 0
same = [[row[i] == col[j] for j in range(N)] for i in range(N)]
for i in range(N):
    for j in range(N):
        if all(same[(i+k) % N][(j+k) % N] for k in range(N)):
            ans += 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
G = [input() for k in range(N)]
ans = 0
for B in range(N):
    temp = [[""]*N for k in range(N)]
    f = 1
    for i in range(N):
        for j in range(N):
            temp[i][j] = G[i][(j+B)%N]
            if temp[j][i] != "":
                if temp[i][j] != temp[j][i]:
                    f = 0
                    break
    ans += f*N

print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N = int(input())
S = np.array([list(input()) for _ in range(N)], dtype="U1")
S = np.concatenate([S, S], axis=1)


def check(x):
    tmp = S[:, x: x + N]
    if (tmp == tmp.T).all():
        return N
    return 0


ans = 0
for x in range(N):
    ans += check(x)

print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np

read = sys.stdin.read
readline = sys.stdin.readline

N, *S = map(str, read().split())
S = np.array(list(map(list, S)), np.str)
S = np.hstack((S, S))
S = np.vstack((S, S))
N = int(N)
answer = 0
for y in range(N):
    a = S[:N, y:y + N]
    if np.all(a == a.T):
        answer += N

print(answer)