๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

[Swift] 2021 KAKAO INTERNSHIP ๊ฑฐ๋ฆฌ๋‘๊ธฐ ํ™•์ธํ•˜๊ธฐ

by Fomagran ๐Ÿ’ป 2021. 8. 7.
728x90
๋ฐ˜์‘ํ˜•

 

Problem

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ฑฐ๋ฆฌ๋‘๊ธฐ ํ™•์ธํ•˜๊ธฐ

[["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]] [1, 0, 1, 1, 1]

programmers.co.kr


Solution

 

1. ์‘์‹œ์ž์˜ ์œ„์น˜๋ฅผ ํŒŒ์•…ํ•œ๋‹ค.

 

func getSeatLocation(places:[String],xMap:inout [[String]],applicants:inout [Seat]) {
    for (y,place) in places.enumerated() {
        xMap.append(place.map{String($0)})
        for (x,p) in place.map({String($0)}).enumerated() {
            if p == "P" {
                applicants.append((x,y))
            }
        }
    }
}

 

2. ๋งจํ•˜ํŠผ ๊ฑฐ๋ฆฌ๊ฐ€ 2์ดํ•˜์ผ ๊ฒฝ์šฐ 3๊ฐ€์ง€ ์กฐ๊ฑด์œผ๋กœ ๊ฒ€์‚ฌํ•œ๋‹ค.

 

    2-1. x์œ„์น˜๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ

 

     y์œ„์น˜๊ฐ€ ๋” ์ ์€ ์‘์‹œ์ž์˜ y์— +1์„ ํ•ด์ค€ ๊ณณ์ด "X"์ธ์ง€ ํ™•์ธํ•œ๋‹ค.

 

    2-2. y์œ„์น˜๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ

 

     x์œ„์น˜๊ฐ€ ๋” ์ ์€ ์‘์‹œ์ž์˜ x์— +1์„ ํ•ด์ค€ ๊ณณ์ด "X"์ธ์ง€ ํ™•์ธํ•˜๋‹ค.

 

    2-3.x์™€ y๋ชจ๋‘ ๋‹ค๋ฅผ ๊ฒฝ์šฐ

 

     x์œ„์น˜๊ฐ€ ๋” ์ ์€ ๊ณณ์€ x์— +1์„ ํ•ด์ค€ ๊ณณ์ด "X"์ธ์ง€ ํ™•์ธํ•˜๊ณ 

 

     x์œ„์น˜๊ฐ€ ๋” ํฐ ๊ณณ์€ x -1์„ ํ•ด์ค€ ๊ณณ์ด "X"์ธ์ง€ ํ™•์ธํ•œ๋‹ค.

 

func getManhattanDistance(p1:Seat,p2:Seat) -> Int {
    return abs(p1.0-p2.0) + abs(p1.1-p2.1)
}

func isKeepDistance(p1:Seat,p2:Seat,xMap:inout [[String]]) -> Bool {
    let minX = p1.0 < p2.0 ? p1 : p2
    let minY = p1.1 < p2.1 ? p1 : p2
    if p1.0 == p2.0 {
        return xMap[minY.1+1][p1.0] == "X"
    }else if p1.1 == p2.1 {
        return xMap[p1.1][minX.0+1] == "X"
    }else {
        if p1.0 < p2.0 {
            return xMap[p1.1][p1.0+1] == "X" && xMap[p2.1][p2.0-1] == "X"
        }else {
            return xMap[p2.1][p2.0+1] == "X" && xMap[p1.1][p1.0-1] == "X"
        }
    }
}

 

3. ๋ชจ๋“  ๋Œ€๊ธฐ์‹ค์„ ๊ฒ€์‚ฌํ•˜๊ณ  ์กฐ๊ฑด์— ๋งž๊ฒŒ 0๊ณผ 1์„ ๋„ฃ์€ ๋’ค ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

func solution(_ places:[[String]]) -> [Int] {
    var answer:[Int] = []
    for place in places {
        var check:Bool = false
        var applicants:[Seat] = []
        var xMap:[[String]] = []
        getSeatLocation(places: place,xMap: &xMap,applicants: &applicants)
        outer:while !applicants.isEmpty {
            let first = applicants.removeFirst()
            for applicant in applicants {
                if getManhattanDistance(p1: first, p2: applicant) <= 2 {
                    if !isKeepDistance(p1: first, p2: applicant,xMap: &xMap) {
                        answer.append(0)
                        check = true
                        break outer
                    }
                }
            }
        }
        if !check {
            answer.append(1)
        }
    }
    return answer
}

Source Code

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€