728x90
๋ฌธ์
ํ์ด
์์ ์ง์ ๊ณผ ๊ฐ์ ๋ฌธ์์ธ ๊ฒฝ์ฐ dfs๋ฅผ ์ํํ๊ณ
๊ธธ์ด๊ฐ 4 ์ด์์ด๊ณ ์์ ์ง์ ์ผ๋ก ๋์์จ ๊ฒฝ์ฐ "Yes"๋ฅผ ์ถ๋ ฅํ๋ฉด ๋๋ค.
์ฝ๋
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
graph = [list(input().rstrip()) for _ in range(n)]
tempVisited = [[False] * m for _ in range(n)]
dir = ((0, 1), (0, -1), (1, 0), (-1, 0))
def dfs(c, sti, stj, nowi, nowj, cnt):
for dx, dy in dir:
ni, nj = nowi + dy, nowj + dx
if (sti, stj) == (ni, nj) and graph[ni][nj] == c and cnt >= 4:
print("Yes")
exit()
if ni < 0 or ni >= n or nj < 0 or nj >= m or tempVisited[ni][nj] or graph[ni][nj] != c: continue
tempVisited[ni][nj] = True
dfs(c, sti, stj, ni, nj, cnt + 1)
for i in range(n):
for j in range(m):
tempVisited = [[False] * m for _ in range(n)]
tempVisited[i][j] = True
dfs(graph[i][j], i, j, i, j, 1)
print("No")
๋ง๋ฌด๋ฆฌ
.
728x90