Showing

[DFS, SWEA] 미로 본문

컴퓨터 공학, 전산학/알고리즘

[DFS, SWEA] 미로

RabbitCode 2023. 12. 22. 21:30

https://swexpertacademy.com/main/learn/course/subjectDetail.do?courseId=AVuPDN86AAXw5UW6&subjectId=AWOVIc7KqfQDFAWg#

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

dy = [-1, 1, 0, 0] 
dx = [0, 0, -1, 1]

T = int(input())
for t in range(T):
    n = int(input())
    arr = [list(map(int, input())) for _ in range(n)]

    start_y, start_x = 0, 0
    for i in range(n):
        for j in range(n):
            if arr[i][j] == 2:
                start_y, start_x = i, j

    def dfs(_y, _x):
        if not (0 <= _y < n and 0 <= _x < n) or arr[_y][_x] == 1:
            return False
        if arr[_y][_x] == 3:
            return True
        arr[_y][_x] = 1  # 방문 표시
        for k in range(4):
            n_y = _y + dy[k]
            n_x = _x + dx[k]
            if 0 <= n_y < n and 0 <= n_x < n and arr[n_y][n_x] != 1:
                if dfs(n_y, n_x):
                    return True
        return False

    result = dfs(start_y, start_x)
    print(f'#{t+1} {1 if result else 0}')