fork download
  1. from sys import stdin
  2.  
  3. input = stdin.readline
  4. """
  5. 왜 시간 초과지 ? -> 어떤 부분을 고쳐야 더 빨라질까 ?
  6. """
  7.  
  8. dys, dxs = [-1, 1, 0, 0], [0, 0, -1, 1]
  9.  
  10. def dfs(y, x, move_cnt):
  11. print(y, x, move_cnt)
  12. # print("***********************")
  13. # print(f"y = {y} / x = {x}")
  14. # for c_y in range(r):
  15. # for c_x in range(c):
  16. # print(visited[c_y][c_x], end=" ")
  17. # print()
  18. # print("***********************")
  19. z = zip(dys, dxs)
  20. ret = move_cnt
  21. for dy, dx in z:
  22. new_y, new_x = y + dy, x + dx
  23. # 범위를 넘지 않고, 지난 적이 없는 알파벳이라면 -> dfs() 탐색
  24. if 0 <= new_y < r and 0 <= new_x < c:
  25. k=alpha_map[new_y][new_x]
  26. if not alpha_set[k]:
  27. continue
  28. alpha_set[k] = False
  29. ret = max(r, dfs(new_y, new_x, move_cnt+1))
  30. # 역순으로 돌려놓는 과정
  31. alpha_set[k] = True # 미방문 처리
  32. return ret
  33.  
  34.  
  35. ## 변수 입력 부분 ##
  36. r, c = map(int, input().split()) # 1 <= r(행), c(열) <= 20
  37. alpha_map = [[ord(x)-65 for x in input().strip()] for _ in range(r)] # 알파벳 보드 정보
  38. alpha_set = [True] * 26 # 지나온 알파벳 목록
  39.  
  40. ## 문제 해결 부분 ##
  41. alpha_set[alpha_map[0][0]] = False
  42. print(dfs(0, 0, 1))
  43.  
Success #stdin #stdout 0.03s 9620KB
stdin
3 6
HFDFFB
AJHGDH
DGAGEH
stdout
0 0 1
1 0 2
2 0 3
2 1 4
1 1 5
0 1 6
1 1 3
0 1 4
0 2 5
2 1 4
2 0 5
0 1 2
1 1 3
2 1 4
2 0 5
1 0 6
2 2 5
1 0 4
2 0 5
2 1 6
0 2 3
3