Problem:


Score : 700 points

Problem Statement

There is an H \times W grid (H vertical, W horizontal), where each square contains a lowercase English letter.
Specifically, the letter in the square at the i-th row and j-th column is equal to the j-th character in the string S_i.

Snuke can apply the following operation to this grid any number of times:

Choose two different rows and swap them. Or, choose two different columns and swap them.

Snuke wants this grid to be symmetric.
That is, for any 1 \leq i \leq H and 1 \leq j \leq W, the letter in the square at the i-th row and j-th column and the letter in the square at the (H + 1 - i)-th row and (W + 1 - j)-th column should be equal.

Determine if Snuke can achieve this objective.

Constraints

1 \leq H \leq 12

1 \leq W \leq 12

|S_i| = W

S_i consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

If Snuke can make the grid symmetric, print YES; if he cannot, print NO.

Sample Input 1

2 3
arc
rac

Sample Output 1

YES

If the second and third columns from the left are swapped, the grid becomes symmetric, as shown in the image below:

Sample Input 2

3 7
atcoder
regular
contest

Sample Output 2

NO

Sample Input 3

12 12
bimonigaloaf
faurwlkbleht
dexwimqxzxbb
lxdgyoifcxid
ydxiliocfdgx
nfoabgilamoi
ibxbdqmzxxwe
pqirylfrcrnf
wtehfkllbura
yfrnpflcrirq
wvcclwgiubrk
lkbrwgwuiccv

Sample Output 3

YES



Sample input:
2 3
arc
rac


Sample output:
YES

Submission status: Wrong Answer

Solution code:
import sys
import copy

sys.setrecursionlimit(10 ** 6)

def main():
    def per(s, a=[]):
        if not s:
            return [a]
        if len(s) % 2:
            cs = copy.deepcopy(s)
            res = []
            for u in cs:
                s.remove(u)
                res += per(s, [u] + a)
                s.add(u)
            return res
        u = min(s)
        s.remove(u)
        cs = copy.deepcopy(s)
        res = []
        for uu in cs:
            if uu < u: continue
            s.remove(uu)
            res += per(s, a + [u, uu])
            s.add(uu)
        s.add(u)
        return res

    ord_a = ord("a")
    h, w = map(int, input().split())
    t0 = [[ord(c) - ord_a for c in input()] for _ in range(h)]
    h_set = set(range(h))
    pattern = per(h_set)
    # print(t0)
    # print(pattern)
    b = h % 2
    for p in pattern:
        t1 = [[] for _ in range(h)]
        if b:
            t1[h // 2] = t0[p[0]]
        for i in range(b, h, 2):
            t1[i - b] = t0[p[i]]
            t1[h - 1 - i + b] = t0[p[i + 1]]
        # print(t1)
        fin = [False] * w
        mid = (w % 2 == 1)
        br = False
        for j, c0 in enumerate(zip(*t1)):
            if fin[j]: continue
            fin[j] = True
            c0 = c0[::-1]
            for jj, c1 in enumerate(zip(*t1)):
                if jj <= j: continue
                if c0 == c1:
                    fin[jj] = True
                    break
            else:
                if mid:
                    mid = False
                else:
                    br = True
                    break
        if br: continue
        print("YES")
        exit()
    else:
        print("NO")

main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)

def main():
    h, w = map(int, input().split())
    row = [[0] * 26 for _ in range(h)]
    col = [[0] * 26 for _ in range(w)]
    ord_a = ord("a")
    ss = [input() for _ in range(h)]
    for i, s in enumerate(ss):
        for j, c in enumerate(s):
            code = ord(c) - ord_a
            row[i][code] += 1
            col[j][code] += 1
    mid = (h % 2 == 1)
    fin = [False] * h
    for i in range(h):
        if fin[i]: continue
        fin[i] = True
        for j in range(i + 1, h):
            if row[i] == row[j]:
                fin[j] = True
                break
        else:
            if mid:
                mid = False
            else:
                print("NO")
                exit()
    mid = (w % 2 == 1)
    fin = [False] * w
    for i in range(w):
        if fin[i]: continue
        fin[i] = True
        for j in range(i + 1, w):
            if col[i] == col[j]:
                fin[j] = True
                break
        else:
            if mid:
                mid = False
            else:
                print("NO")
                exit()
    print("YES")

main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)

def main():
    h,w=map(int, input().split())
    al=[0]*26
    ord_a=ord("a")
    ss=[input() for _ in range(h)]
    for s in ss:
        for c in s:
            i=ord(c)-ord_a
            al[i]+=1
    if h%2 and w%2:
        c=ss[h//2][w//2]
        i = ord(c) - ord_a
        al[i] -= 1
    for k in al:
        if k%2:
            print("NO")
            break
    else:
        print("YES")

main()

Submission status: Wrong Answer

Solution code:
from itertools import groupby
H, W = map(int, input().split())
S = ["" for _ in range(W)]
T = []
for _ in range(H):
    s = input()
    T.append(s)
    for i, c in enumerate(s):
        S[i] += c
T = [sorted(t) for t in T]
S = [sorted(s) for s in S]
T.sort()
S.sort()
cnt = 0
for _, g in groupby(T):
    if len(list(g))%2:
        cnt += 1
if H%2 < cnt:
    print("NO")
    exit()
cnt = 0
for _, g in groupby(S):
    if len(list(g))%2:
        cnt += 1
if W%2 < cnt:
    print("NO")
    exit()
print("YES")

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
import itertools
import numpy as np
from scipy.sparse.csgraph import connected_components

H,W = map(int,input().split())
words = np.array([list(input().rstrip()) for _ in range(H)], dtype='U1')

def gen_pair_pattern_even(rest):
    # 偶数個を仮定
    if len(rest) == 0:
        yield []
        return
    if len(rest) == 1:
        x = rest.pop()
        yield [(x,x)]
        return
    li = list(rest)
    x = li[0]
    for y in li[1:]:
        se = rest.copy()
        se.remove(x)
        se.remove(y)
        for p in gen_pair_pattern_even(se):
            yield p + [(x,y)]    

def gen_pair_pattern(N):
    if N & 1:
        for n in range(N):
            se = set(x for x in range(N) if x != n)
            for p in gen_pair_pattern_even(se):
                yield p + [(n,n)]
    else:
        for p in gen_pair_pattern_even(set(range(N))):
            yield p

def test(row_pairs):
    graph = np.ones((W,W), dtype = np.bool)
    for r1,r2 in row_pairs:
        graph &= (words[r1][:,None] == words[r2][None,:])
    se = set(range(W))
    while se:
        removed = False
        for i,j in itertools.combinations(se,2):
            if graph[i,j]:
                se.remove(i)
                se.remove(j)
                removed = True
                break
        if not removed:
            break
    if len(se) > 1:
        return False
    return True

bl = False
for p in gen_pair_pattern(H):
    if test(p):
        bl = True
        break

answer = 'YES' if bl else 'NO'
print(answer)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

orda = ord('a')
p12 = 2 ** 12

s = None
ts = None
h = None
w = None

row_keys = None
col_keys = None


def calc_row_keys(sel = 0, count = 0, last = -1):
    if count == w // 2:
        arr = []
        row_keys[sel] = arr
        for i in range(h):
            si = s[i]
            ss = []
            for j in range(w):
                if sel & (2 ** j):
                    ss.append(si[j])
            ss.sort()
            v = 0
            for ch in ss:
                v *= 26
                v += ord(ch) - orda
            arr.append(v)
    else:
        for j in range(last + 1, w):
            calc_row_keys(sel | (2 ** j), count + 1, j)


def calc_col_keys(sel = 0, count = 0, last = -1):
    if count == h // 2:
        arr = []
        col_keys[sel] = arr
        for j in range(w):
            sj = ts[j]
            ss = []
            for i in range(h):
                if sel & (2 ** i):
                    ss.append(sj[i])
            ss.sort()
            v = 0
            for ch in ss:
                v *= 26
                v += ord(ch) - orda
            arr.append(v)
    else:
        for i in range(last + 1, h):
            calc_col_keys(sel | (2 ** i), count + 1, i)


def check_sym1(t):
    c = 0
    for ch in t:
        c ^= 2 ** (ord(ch) - orda)
    odd = 0
    for code in range(26):
        if c & (2 ** code):
            odd += 1
    return odd <= 1


def check_sym(sel_rows, sel_rows2, center_row = None, sel_cols = None, sel_cols2 = None, center_col = None):
    if sel_cols is None:
        t0 = 2 ** w - 1
        if w % 2:
            for j in range(w):
                p2j = 2 ** j
                t = t0 - p2j
                for sel_cols in row_keys.keys():
                    if sel_cols & p2j:
                        continue
                    sel_cols2 = t - sel_cols
                    if sel_cols2 < sel_cols:
                        continue
                    if check_sym(sel_rows, sel_rows2, center_row, sel_cols, sel_cols2, j):
                        return True
            return False
        else:
            for sel_cols in row_keys.keys():
                sel_cols2 = t0 - sel_cols
                if sel_cols2 < sel_cols:
                    continue
                if check_sym(sel_rows, sel_rows2, center_row, sel_cols, sel_cols2):
                    return True
            return False
    else:
        rows = []
        rows2 = []
        keys = row_keys[sel_cols]
        keys2 = row_keys[sel_cols2]
        for i in range(h):
            p2i = 2 ** i
            if p2i & sel_rows:
                rows.append((keys[i], keys2[i], i))
            elif p2i & sel_rows2:
                rows2.append((keys2[i], keys[i], i))
        rows.sort()
        rows2.sort()
        for i in range(len(rows)):
            if rows[i][0] != rows2[i][0]:
                return False
            if rows[i][1] != rows2[i][1]:
                return False
        if center_col is not None:
            sc = ts[center_col]
            for i in range(len(rows)):
                if sc[rows[i][2]] != sc[rows2[i][2]]:
                    return False
        cols = []
        cols2 = []
        keys = col_keys[sel_rows]
        keys2 = col_keys[sel_rows2]
        for j in range(w):
            p2j = 2 ** j
            if p2j & sel_cols:
                cols.append((keys[j], keys2[j], j))
            elif p2j & sel_cols2:
                cols2.append((keys2[j], keys[j], j))
        cols.sort()
        cols2.sort()
        for j in range(len(cols)):
            if cols[j][0] != cols2[j][0]:
                return False
            if cols[j][1] != cols2[j][1]:
                return False
        if center_row is not None:
            sc = s[center_row]
            for j in range(len(cols)):
                if sc[cols[j][2]] != sc[cols2[j][2]]:
                    return False
        for i in range(len(rows)):
            si = s[rows[i][2]]
            si2 = s[rows2[i][2]]
            for j in range(len(cols)):
                if si[cols[j][2]] != si2[cols2[j][2]]:
                    return False

    return True


def solve():
    global row_keys, col_keys
    global ts

    if h == 1 or w == 1:
        if h == 1:
            s0 = s[0]
        else:
            s0 = ''.join(s)
        return check_sym1(s0)

    ts = ['' for _ in range(w)]
    for i in range(h):
        si = s[i]
        for j in range(w):
            ts[j] += si[j]

    row_keys = {}
    col_keys = {}
    calc_row_keys()
    calc_col_keys()

    t0 = 2 ** h - 1
    if h % 2:
        for i in range(h):
            p2i = 2 ** i
            t = t0 - p2i
            for sel_rows in col_keys.keys():
                if sel_rows & p2i:
                    continue
                sel_rows2 = t - sel_rows
                if sel_rows2 < sel_rows:
                    continue
                if check_sym(sel_rows, sel_rows2, i):
                    return True
    else:
        for sel_rows in col_keys.keys():
            sel_rows2 = t0 - sel_rows
            if sel_rows2 < sel_rows:
                continue
            if check_sym(sel_rows, sel_rows2):
                return True

    return False


def main():
    global s, h, w

    h, w = input().split()
    h = int(h)
    w = int(w)
    s = [input() for _ in range(h)]


    print('YES' if solve() else 'NO')


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
G=[list(input()) for i in range(H)]
G_t=[list(x) for x in list(zip(*G))]
def Check(G,H,W):
  Paired_y=[False]*H
  for y1 in range(H):
    if Paired_y[y1]:
      continue
    for y2 in range(H):
      if y1==y2 or Paired_y[y2]:
        continue
      Paired_x=[False]*W
      for x1 in range(W):
        if Paired_x[x1]:
          continue
        for x2 in range(W):
          if x1==x2 or Paired_x[x2]:
            continue
          if G[y1][x1]==G[y2][x2] and G[y1][x2]==G[y2][x1]:
            Paired_x[x1]=True
            Paired_x[x2]=True
            break
      if W%2==1:
        if Paired_x.count(False)==1:
          r=Paired_x.index(False)
          if G[y1][r]==G[y2][r]:
            Paired_y[y1]=True
            Paired_y[y2]=True
      else:
        if Paired_x.count(False)==0:
          Paired_y[y1]=True
          Paired_y[y2]=True
  if H%2==1:
    if Paired_y.count(False)==1:
      return True
    else:
      return False
  else:
    if Paired_y.count(False)==0:
      return True
    else:
      return False
  
if Check(G,H,W) and Check(G_t,W,H):
  print("YES")
else:
  print("NO")

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
G=[list(input()) for i in range(H)]
G_t=[list(x) for x in list(zip(*G))]
def Check(G,H,W):
  Paired_y=[False]*H
  for y1 in range(H):
    if Paired_y[y1]:
      continue
    for y2 in range(H):
      if y1==y2 or Paired_y[y2]:
        continue
      Paired_x=[False]*W
      for x1 in range(W):
        if Paired_x[x1]:
          continue
        for x2 in range(W):
          if x1==x2 or Paired_x[x2]:
            continue
          if G[y1][x1]==G[y2][x2] and G[y1][x2]==G[y2][x1]:
            Paired_x[x1]=True
            Paired_x[x2]=True
            break
      if W%2==1:
        if Paired_x.count(False)==1:
          Paired_y[y1]=True
          Paired_y[y2]=True
      else:
        if Paired_x.count(False)==0:
          Paired_y[y1]=True
          Paired_y[y2]=True
  if H%2==1:
    if Paired_y.count(False)==1:
      return True
    else:
      return False
  else:
    if Paired_y.count(False)==0:
      return True
    else:
      return False
  
if Check(G,H,W) and Check(G_t,W,H):
  print("YES")
else:
  print("NO")

Submission status: Wrong Answer

Solution code:
input = raw_input
range = xrange

n, m = map(int,input().split())
grid = [input() for i in range(n)]

use = [False]*n
cur = []
def backtrack(i, rem):
    if rem == 0: return check(cur)
    if use[i]: return backtrack(i+1, rem)
    if rem == 1:
        use[i] = True; cur.append(i)
        backtrack(i+1, 0)
        use[i] = False; cur.pop()
    use[i] = True; cur.append(i)
    for j in range(i+1, n):
        if use[j]: continue
        use[j] = True; cur.append(j)
        backtrack(i+1, rem-2)
        use[j] = False; cur.pop()
    use[i] = False; cur.pop()

middle_initial = (m%2 == 0)
from collections import Counter
def check(cur):
    P = cur[::2] + cur[1::2][::-1]
    cols = Counter((''.join(grid[P[i]][j] for i in range(n))) for j in range(m))
    middle_filled = middle_initial
    rem = m
    while rem:
        w = next(iter(cols))
        cols[w]-= 1; rem-= 1
        if cols[w] == 0: del cols[w]
        w2 = w[::-1]
        if w2 in cols:
            assert cols[w2]
            cols[w2]-= 1; rem-= 1
            if cols[w2] == 0: del cols[w2]
        elif w == w[::-1] and not middle_filled:
            middle_filled = True
        else: return False
    print("YES"); exit()

backtrack(0, n)
print("NO")

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
s = []
for i in range(h):
  a = input()
  for j in a:
    s.append(j)
import collections
c = collections.Counter(s)
b = list(c.values())
ans = 0
for i in b:
  if i%2 == 1:
    ans += 1
  if ans >= 2:
    print("NO")
    exit()
print("YES")

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
s = []
for i in range(h):
  a = input()
  for j in a:
    s.append(a)
import collections
c = collections.Counter(s)
b = list(c.values())
ans = 0
for i in b:
  if i%2 == 1:
    ans += 1
  if ans >= 2:
    print("NO")
    exit()
print("YES")

Submission status: Wrong Answer

Solution code:
H,W = map(int,input().split())
src = [input() for i in range(H)]

def exist_valid_ptn(grid):
    usedcol = [0] * W
    center_available = W%2
    for i in range(W-1):
        if usedcol[i]: continue
        for j in range(i+1,W):
            if usedcol[j]: continue
            trans = list(zip(*grid))
            icol, jcol = trans[i],trans[j]
            for a,b in zip(icol, jcol[::-1]):
                if a != b: break
            else:
                #found i-j pair
                usedcol[j] = 1
                break
        else:
            if center_available:
                usedcol[i] = 1
                center_available = False
            else:
                return False
    return True

def swap_and_check(used):
    if H - bin(used).count('1') < 2:
        if exist_valid_ptn(src):
            print('YES')
            exit()
        return
    for i in range(H-1):
        if (used>>i) & 1: continue
        for j in range(i+1,H):
            if (used>>j) & 1: continue
            src[i],src[j] = src[j],src[i]
            swap_and_check(used|(1<<i)|(1<<j))
            src[i],src[j] = src[j],src[i]
        used |= (1<<i)

if exist_valid_ptn(src):
    print('YES')
    exit()
swap_and_check(0)
print('NO')

Submission status: Wrong Answer

Solution code:
H,W = map(int,input().split())
src = [input() for i in range(H)]

def exist_valid_ptn(grid):
    usedcol = [0] * W
    center_available = W%2
    for i in range(W-1):
        if usedcol[i]: continue
        for j in range(i+1,W):
            if usedcol[j]: continue
            trans = list(zip(*grid))
            icol, jcol = trans[i],trans[j]
            for a,b in zip(icol, jcol[::-1]):
                if a != b: break
            else:
                #found i-j pair
                usedcol[j] = 1
                break
        else:
            if center_available:
                usedcol[i] = 1
                center_available = False
            else:
                return False
    return True

row_swap_ptns = [[]]
def make_swap_ptns(ptns, used):
    if H - bin(used).count('1') < 2:
        row_swap_ptns.append(ptns)
        return
    for i in range(H-1):
        if (used>>i) & 1: continue
        for j in range(i+1,H):
            if (used>>j) & 1: continue
            make_swap_ptns(ptns + [(i,j)], used|(1<<i)|(1<<j))
        used |= (1<<i)

make_swap_ptns([], 0)

for swapptn in row_swap_ptns:
    for a,b in swapptn:
        src[a],src[b] = src[b],src[a]
    if exist_valid_ptn(src):
        print('YES')
        exit()
    for a,b in swapptn:
        src[a],src[b] = src[b],src[a]
print('NO')

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
lis = [0 for i in range(26)]
for _ in range(n):
  s = list(str(input()))
  for i in range(m):
    lis[ord(str(s[i])) -ord("a")] += 1
if n % 2 == 0 or m % 2 == 0:
  for i in range(26):
    if lis[i] % 2 == 1:
      print("NO")
      exit()
  print("YES")
else:
  cou = 0
  for i in range(26):
    if lis[i] % 2 == 1:
      cou += 1
    if cou > 1:
      print("NO")
      exit()
  print("YES")

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
lis = [0 for i in range(26)]
for _ in range(n):
  s = list(str(input()))
  for i in range(m):
    lis[ord(str(s[i])) -ord("a")] += 1
if n % 2 == 0 and m % 2 == 0:
  for i in range(26):
    if lis[i] % 2 == 1:
      print("NO")
      exit()
  print("YES")
else:
  cou = 0
  for i in range(26):
    if lis[i] % 2 == 1:
      cou += 1
    if cou > 1:
      print("NO")
      exit()
  print("YES")

Submission status: Wrong Answer

Solution code:
h,w = list(map(int,input().split()))
s = []
for i in range(h):
    s.append(input())

con = []

for i in range(h):
    for j in range(i+1,h):
        ij = []
        ji = []
        for k in range(w):
            ij.append(s[i][k]+s[j][k])
            ji.append(s[j][k]+s[i][k])
        if sorted(ij) == sorted(ji):
            con.append([i,j])

rest = set()
for i in range(h):
    rest.add(i)
for x in con:
    if x[0] in rest and x[1] in rest:
        rest -= {x[0],x[1]}

if len(rest) == 0:print('YES')
elif len(rest) == 1:
    tar = s[list(rest)[0]]
    se = set()
    for x in tar:
        if x in se:se -= {x}
        else:se.add(x)
    if len(se) <= 1:
        print('YES')
    else:print('NO')
else:print('NO')

Submission status: Wrong Answer

Solution code:
h,w = list(map(int,input().split()))
s = []
for i in range(h):
    s.append(input())

con = []

for i in range(h):
    for j in range(i+1,h):
        ij = []
        ji = []
        for k in range(w):
            ij.append(s[i][k]+s[j][k])
            ji.append(s[j][k]+s[i][k])
        if sorted(ij) == sorted(ji):
            con.append([i,j])

rest = set()
for i in range(h):
    rest.add(i)
for x in con:
    if x[0] in rest and x[1] in rest:
        rest -= {x[0],x[1]}

if len(rest) == 0:print('YES')
elif len(rest) == 1 and [list(rest)[0],list(rest)[0]] in con:print('YES')
else:print('NO')

Submission status: Wrong Answer

Solution code:
h,w = list(map(int,input().split()))
s = []
for i in range(h):
    s.append(input())

con = []

for i in range(h):
    for j in range(i+1,h):
        ij = []
        ji = []
        for k in range(w):
            ij.append(s[i][k]+s[j][k])
            ji.append(s[j][k]+s[i][k])
        if sorted(ij) == sorted(ji):
            con.append([i,j])

rest = set()
for i in range(h):
    rest.add(i)
for x in con:
    if x[0] in rest and x[1] in rest:
        rest -= {x[0],x[1]}

if len(rest) <= 1:print('YES')
else:print('NO')

Submission status: Wrong Answer

Solution code:
h,w = list(map(int,input().split()))
s = []
for i in range(h):
    s.append(input())

con = []

for i in range(h):
    for j in range(i+1,h):
        ij = []
        ji = []
        for k in range(w):
            ij.append(s[i][k]+s[j][k])
            ji.append(s[j][k]+s[i][k])
        if sorted(ij) == sorted(ji):
            con.append([i,j])

rest = set()
for i in range(h):
    rest.add(i)
for x in con:
    if x[0] in rest and x[1] in rest:
        rest -= {x[0],x[1]}

if len(rest) <= 1:print('Yes')
else:print('No')

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())

h_line = []
w_line = [[] for _ in range(w)]

for _ in range(h):
    s = input()
    h_line.append(sorted(s))
    for i in range(w):
        w_line[i].append(s[i])
for i in range(w):
    w_line[i].sort()

h_line.sort()
w_line.sort()

def check(num, list):
    i = 0
    single = 0
    while i < num:
        if i < num-1 and list[i] == list[i+1]:
            i += 2
        else:
            single += 1
            i += 1
    return( single < 2)

if check(h, h_line ) and check(w, w_line):
    print('YES')
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())

h_line = []
w_line = [[] for _ in range(w)]

for _ in range(h):
    s = input()
    h_line.append(sorted(s))
    for i in range(w):
        w_line[i].append(s[i])
for i in range(w):
    w_line[i].sort()

h_line.sort()
w_line.sort()

i = 0
h_single = 0
while i < h:
    if i == h-1:
        h_single += 1
        i += 1
    elif h_line[i] == h_line[i+1]:
        i += 2
    else:
        h_single += 1
        i += 1

i = 0
w_single = 0
while i < w:
    if i == w-1:
        w_single += 1
        i += 1
    elif w_line[i] == w_line[i+1]:
        i += 2
    else:
        w_single += 1
        i += 1
if h_single < 2 and w_single < 2:
    print('YES')
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
St = [[S[i][j] for i in range(H)] for j in range(W)]

S_sorted = list(map(sorted, S))
St_sorted = list(map(sorted, St))

def count_miss(s):
    idxs = []
    length = len(s)
    counter = 0
    for i in range(length-1):
        if not(i in idxs):
            for j in range(i+1, length):
                if s[i] == s[j]:
                    idxs.append(j)
                    break
                if j == length-1:
                    counter += 1
    if not(length-1 in idxs):
        counter += 1

    return counter
    
missH = count_miss(S_sorted)
missW = count_miss(St_sorted)

if (H*W)%2 == 1:
    if missH < 2 and missW < 2:
        ans = 'YES'
    else:
        ans = 'NO'
else:
    if missH*missW == 0:
        ans = 'YES'
    else:
        ans = 'NO'

print(ans)

Submission status: Wrong Answer

Solution code:
h,w = map(int, input().strip().split())
ss = [input().strip() for i in range(h)]

def check_pair(sorted_ss, length):
    if length % 2 == 0:
        for i in range(length//2):
            if sorted_ss[2*i] != sorted_ss[2*i+1]:
                return False
    elif length % 2 == 1:
        odd = 0
        for i in range(length//2):
            if sorted_ss[2*i] != sorted_ss[2*i+1]:
                if odd == 0:
                    sorted_ss.pop(2*i)
                    odd = 1
                else:
                    return False
    return True

sorted_ss = sorted([''.join(sorted(s)) for s in ss])
flag1 = check_pair(sorted_ss, h)
        
sorted_ss = sorted([''.join(sorted([s[j] for s in ss]))] for j in range(w))
flag2 = check_pair(sorted_ss, w)

if flag1 and flag2:
    print('YES')
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
h,w = map(int, input().strip().split())
ss = [input().strip() for i in range(h)]

def check_pair(sorted_ss, length):
    if length % 2 == 0:
        for i in range(length//2):
            if sorted_ss[2*i] != sorted_ss[2*i+1]:
                return False
    elif length % 2 == 1:
        odd = 0
        for i in range(length//2):
            if sorted_ss[2*i] != sorted_ss[2*i+1]:
                if odd == 0:
                    sorted_ss.pop(2*i)
                    odd = 1
                else:
                    return False
        if odd != 1:
            return False
    return True

sorted_ss = sorted([''.join(sorted(s)) for s in ss])
flag1 = check_pair(sorted_ss, h)
        
sorted_ss = sorted([''.join(sorted([s[j] for s in ss]))] for j in range(w))
flag2 = check_pair(sorted_ss, w)

if flag1 and flag2:
    print('YES')
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
import numpy as np

n, m = map(int, input().split())
d = {i: {chr(i): 0 for i in range(ord('a'), ord('z') + 1)} for i in range(n)}
d2 = {i: {chr(i): 0 for i in range(ord('a'), ord('z') + 1)} for i in range(m)}

lst = []
for i in range(n):
    s = input()
    lst.append(s)
    for j in s:
        d[i][j] += 1
    for j in range(len(s)):
        d2[j][s[j]] += 1

matrix = np.matrix(lst)

k = [0 for i in range(n)]
k2 = [0 for i in range(m)]

f = True
for i in range(n):
    for j in range(n):
        if d[i] == d[j]:
            k[i] += 1

for i in range(m):
    for j in range(m):
        if d2[i] == d2[j]:
            k2[i] += 1

ii = -1
k_0 = []
k_1 = []
k2 = sorted(k2)
k = sorted(k)
if n % 2:
    if len(k) > 1:
        if k[1] < 2:
            f = False

    for i in range(n):
        fl = False
        for j in range(n):
            if j != i:
                if d[i] == d[j]:
                    fl = True
        if not fl:
            ii = i
    if ii != -1:
        s0 = lst[ii]
        if len(s0) % 2:
            for i in s0:
                k_0.append(s0.count(i))
            k_0 = sorted(k_0)
            if len(k_0) > 1:
                for i in range(1, len(k_0)):
                    if k_0[i] % 2:
                        f = False
        else:
            for i in s0:
                k_0.append(s0.count(i))
            k_0 = sorted(k_0)
            for i in range(len(k_0)):
                if k_0[i] % 2:
                    f = False

else:
    if k[0] < 2:
        f = False

ii = -1

if m % 2:
    if len(k2) > 1:
        if k2[1] < 2:
            f = False

    for i in range(m):
        fl = False
        for j in range(m):
            if j != i:
                if d2[i] == d2[j]:
                    fl = True
        if not fl:
            ii = i
    if ii != -1:
        s0 = ''
        for i in range(n):
            s0 += lst[i][ii]

        if len(s0) % 2:
            for i in s0:
                k_1.append(s0.count(i))
            k_1 = sorted(k_1)
            if len(k_1) > 1:
                for i in range(1, len(k_1)):
                    if k_1[i] % 2:
                        f = False
        else:
            for i in s0:
                k_1.append(s0.count(i))
            k_1 = sorted(k_1)
            for i in range(len(k_1)):
                if k_1[i] % 2:
                    f = False

else:
    if k2[0] < 2:
        f = False
        
if n == 1:
    if lst[0] == lst[0][::-1]:
        f = True


if f:
    print('YES')
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
n, m = map(int,input().split())
d = {i: {chr(i): 0 for i in range(ord('a'), ord('z')+1)} for i in range(n)}
d2 = {i: {chr(i): 0 for i in range(ord('a'), ord('z')+1)} for i in range(m)}
for i in range(n):
    s = input()
    for j in s:
        d[i][j] += 1
    for j in range(len(s)):
        d2[j][s[j]] += 1
 
k = [0 for i in range(n)]
k2 = [0 for i in range(m)]
 
f = True
for i in range(n):
    for j in range(n):
        if d[i] == d[j]:
            k[i] += 1
 
 
for i in range(m):
    for j in range(m):
        if d2[i] == d2[j]:
            k2[i] += 1
 
k2 = sorted(k2)
k = sorted(k)
if n % 2:
    if len(k) > 1:
        if k[1] < 2:
            f = False
else:
    if k[0] < 2:
        f = False
 
if m % 2:
    if len(k2) > 1:
        if k2[1] < 2:
            f = False
else:
    if k2[0] < 2:
        f = False
 
if f:
    print('YES')
else:
    print('NO')