문제 풀이

import Foundation

func solution(_ places:[[String]]) -> [Int] {
    
    var answers: [Int] = []
    
    places.forEach { place in
        var place = place.map { $0.map { String($0) } }
        
        for j in 0..<5 {
            for i in 0..<5 {                // 강의실을 0,0 부터 순회
                if place[j][i] == "P" {     // P를 발견하면 탐색시작
                    place[j][i] = "X"       // 다시 역방향으로 탐색했을 때 기준 P를 다른 참가자로 오인하면 안되므로
                    if !check(y: j, x: i, n: place.count, place: place) { // 체크해서 false나오면 0 append 하고 순회 종료
                        answers.append(0)   
                        return
                    }
                    place[j][i] = "P" // 다시 돌려준다.
                }
            }
        }
        answers.append(1) // 순회가 무사히 끝나면 1 append
    }
    
    return answers
}

func check(y: Int, x: Int, n: Int,place: [[String]], d: Int = 0, isStart: Bool = true) -> Bool {
    let dy = [0, 0, 1 , -1]
    let dx = [1, -1, 0 , 0]
    
    if place[y][x] == "P" && d <= 2 && !isStart { 
        return false
    } else if d > 2 {
        return true
    }
    
    for i in 0...3 {
        let ny = dy[i] + y
        let nx = dx[i] + x
        let nd = d + abs(ny - y) + abs(nx - x)
        
        if ny < n && ny >= 0 && nx < n && nx >= 0 && place[ny][nx] != "X" {
            if !check(y: ny, x: nx, n: n, place: place, d: nd, isStart: false) {
                return false
            }
        }
    }
    
    return true
}

참고 : https://programmers.co.kr/learn/courses/30/lessons/81302