DevYoon
[SWEA] 2105. ๋์ ํธ ์นดํ (Python) ๋ณธ๋ฌธ
link ๐ https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5VwAr6APYDFAWu
def dfs(num, cy, cx, visit):
global Max, sy, sx
if num > 3:
return
if num == 3 and cy == sy and cx == sx:
if Max < len(visit):
Max = len(visit)
return
for idx in range(num, num+2): # ํ์ฌ ๋ฐฉํฅ, ํ์ฌ๋ฐฉํฅ+1
dy, dx = cy+directy[idx], cx+directx[idx]
if 0 <= dy < n and 0 <= dx < n:
if arr[dy][dx] not in visit:
visit.append(arr[dy][dx])
dfs(idx, dy, dx, visit)
visit.pop()
t = int(input())
for tc in range(1, t+1):
n = int(input())
arr = [list(map(int, input().split())) for _ in range(n)]
Max = -1
directy = [1, 1, -1, -1, 100] # 4๋ฒ์งธ๋ ์ธ๋ฑ์ค๋ฅผ ๋ฒ์ด๋ ๊ฒฝ์ฐ๋ฅผ ๋๋นํด์ ์๋ฌด ์ซ์๋
directx = [-1, 1, 1, -1, 100]
for y in range(n-2):
for x in range(1, n-1): # 0์ด๊ณผ n-1์ด์ ์ฌ๊ฐํ ์์ฑ ๋ถ๊ฐ๋ฅ
sy, sx = y, x # ์์์ ๋ณ์ ๋ง๋ค์ด ์ฃผ๊ธฐ
dfs(0, sy, sx, []) # ๋ฐฉํฅ, y์ขํ, x์ขํ, visit
print(f'#{tc} {Max}')
๐ฅ ์ฃผ์
- ํ............^^
- DFS๋ฅผ ์ด๋ ๊ฒ๋ ํ์ฉํ ์ ์๊ตฌ๋ ๋ ๋ฐฐ์ ๋คใ ใ
- ๊ผญ ํ ๋ฒ ๋ ํ์ด๋ณผ ๊ฒ