π―μ νμ μΈ DFSλ¬Έμ λΌλ μκ°μ΄ λ€μμ.
κ·Όλ° μν loopλ₯Ό ꡬνλ μμΈ μ§νμ² 2νΈμ μ μ΄λ―Έ νμκΈ° λλ¬Έμ λ μ½κ² ν μ μμλ κ² κ°λ€. λ€λ§! μ΄ λ¬Έμ λ matrix ꡬ쑰λΌμ κ·Έμ λ§κ² λ¬Έμ λ§ λ³νν΄μ£Όλ©΄ λμμ!
μ²μμ μλ¬κ° λ΄μλλ° μ΄λμ λ΄λλ©΄..
# μ΄λ κ² νλ©΄ νλ² νμνκ³ μ΄μ κ² λ°©λ¬Έ νμ λμ΄μ λ°λ‘ True λ°νν¨.
elif 0<=nx<n and 0<=ny<m and card[nx][ny] == color and \
visit[nx][ny] is True and cnt >= 2:
λ°λ‘ μ΄ λΆλΆμ΄λ€.. λ€μ λ
Έλ νμν λ λ°λ‘ μ΄μ λ
Έλκ° μ‘°κ±΄μ κ±Έλ €λ²λ¦Ό...
κ·Έλμ μκ°μ νλ€κ° κ·Έλ₯ κ° λ
Έλμ λν΄μ μνμΈμ§ νμ
νλ μμΈ μ§νμ² 2νΈμ λ¬Έμ μ²λΌ νμ΄μΌ λκ² κ΅¬λ μ΄ μκ°μ΄ λ¦.
πstart node is next node λΌλ©΄ μνμ μ΄λΌλ λ‘μ§μ μ΄μ©νμ
λκ° brute force λλμΌλ‘ νμ΄λ²λ €μ μ¬μ€ λ°νμ μλ¬ λ° μ€ μμλλ° μ λ¨λλΌκ³ ... 보λκΉ data κ°―μκ° μμ² μ μμ. ν ... μΌλ¨ λμ€μ μ’ λ μ’μ μκ³ λ¦¬μ¦ μκ°ν΄ λ΄μΌκ²λ€.. νΌκ³€ν΄μ μλ¬ κ°μΌν¨ γ γ
import sys
sys.stdin = open('test.txt', 'r')
n, m = map(int, input().split())
# print μ°μ΄λ³΄λ©΄ κ°ν λ€μ΄μμ΄μ rstrip μ΄μ©
card = [list(sys.stdin.readline().rstrip()) for _ in range(n)]
flag = False
def dfs(start, next, color, visit, cnt):
global flag
a, b = next
visit[a][b] = True
for i in range(4):
nx = a + dx[i]
ny = b + dy[i]
# λ²μ μμ΄κ³ κ°μ 컬λ¬μ΄λ©΄μ λ°©λ¬Ένμ§ μμμ λ
if 0<=nx<n and 0<=ny<m and card[nx][ny] == color and visit[nx][ny] is False:
dfs(start, (nx,ny), color, visit, cnt + 1)
# λ²μ μμ΄κ³ κ°μ 컬λ¬μ΄λ©΄μ λ°©λ¬Ένλ€λ©΄ μνꡬ쑰
# μ΄λ κ² νλ©΄ νλ² νμνκ³ μ΄μ κ² λ°©λ¬Έ νμ λμ΄μ λ°λ‘ True λ°νν¨.
elif start == (nx, ny) and 0<=nx<n and 0<=ny<m and card[nx][ny] == color and visit[nx][ny] is True and cnt >= 2:
flag = True
return
dx=[1,-1,0,0]
dy=[0,0,1,-1]
for i in range(n):
for j in range(m):
visit = [[False] * m for _ in range(n)]
dfs((i,j),(i,j), card[i][j], visit, 0)
if flag is True:
print("Yes")
else:
print("No")