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

[Swift] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์œ„ํด๋ฆฌ ์ฑŒ๋ฆฐ์ง€ 9์ฃผ์ฐจ ์ „๋ ฅ๋ง์„ ๋‘˜๋กœ ๋‚˜๋ˆ„๊ธฐ

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

Problem

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - 9์ฃผ์ฐจ

9 [[1,3],[2,3],[3,4],[4,5],[4,6],[4,7],[7,8],[7,9]] 3 7 [[1,2],[2,7],[3,7],[3,4],[4,5],[6,7]] 1

programmers.co.kr


Solution

 

1. ์ „์„ ๋ง์˜ ์—ฐ๊ฒฐ ์ •๋ณด๋ฅผ connect ์ด์ค‘๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์„œ ์ €์žฅํ•œ๋‹ค.

 

 var connect = Array(repeating: Array(repeating: false, count: n+1), count:n+1)

wires.forEach {
        connect[$0[0]][$0[1]] = true
        connect[$0[1]][$0[0]] = true
    }

 

2. ์—ฐ๊ฒฐ๋œ ์ „์„ ์„ ํ•˜๋‚˜์”ฉ ์ž˜๋ผ๋ณด๋ฉฐ ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ์˜ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ์ฃผ๊ณ  ์ตœ์†Ÿ๊ฐ’๊ณผ ๋น„๊ตํ•ฉ๋‹ˆ๋‹ค.

 

์šฐ์„  ์ตœ์†Ÿ๊ฐ’์„ ์ €์žฅํ•˜๋Š” minCount ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค.

 

๋งŒ์•ฝ 1๊ณผ 3์ด ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋‹ค๋ฉด ์ด ์—ฐ๊ฒฐ์„ ๋Š๊ณ  1๊ณผ ์—ฐ๊ฒฐ๋œ ์ „์„ ์˜ ๊ฐฏ์ˆ˜(leftCount)์™€

 

3๊ณผ ์—ฐ๊ฒฐ๋œ ์ „์„ ์˜ ๊ฐฏ์ˆ˜(rightCount)๋ฅผ ๋บ€ ๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ๋” ์ž‘์€ ๊ฐ’์„ ์ตœ์†Ÿ๊ฐ’์œผ๋กœ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค.

 

var minCount:Int = Int.max

wires.forEach {
        var leftCount:Int = 0
        var rightCount:Int = 0
        countConnectingWire(parent: nil, start: $0[0],stop: $0[1], count: &leftCount,connect: connect)
        countConnectingWire(parent: nil, start: $0[1],stop: $0[0] ,count: &rightCount,connect: connect)
        minCount = min(minCount,abs(leftCount-rightCount))
    }

 

3. dfs๋กœ ํŠน์ • ์ „์„ ์ด ๋‹ค๋ฅธ ์ „์„ ๊ณผ ์—ฐ๊ฒฐ๋œ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ์ค€๋‹ค.

 

์œ„์—์„œ ์ €์žฅํ•œ connect ์ •๋ณด๋ฅผ ํ†ตํ•ด์„œ ์—ฐ๊ฒฐ๋œ ์ „์„ ์„ ํ•„ํ„ฐ๋ง ํ•ด์ค๋‹ˆ๋‹ค.

 

๋ฌดํ•œ๋ฃจํ”„๋ฅผ ๋ง‰๊ธฐ ์œ„ํ•ด ๋ฐ”๋กœ ๊ทธ ์ „ ๋…ธ๋“œ(parent)์™€ stop(์™ผ์ชฝ์˜ ์ „์„ ์ผ ๊ฒฝ์šฐ ์˜ค๋ฅธ์ชฝ,์˜ค๋ฅธ์ชฝ์˜ ์ „์„ ์ผ ๊ฒฝ์šฐ ์™ผ์ชฝ)์ผ ๊ฒฝ์šฐ๋ฅผ

 

์ œ์™ธํ•œ ๊ฐฏ์ˆ˜๋ฅผ count์— ๋”ํ•ด์ค๋‹ˆ๋‹ค.

 

func countConnectingWire(parent:Int?,start:Int,stop:Int,count:inout Int,connect:[[Bool]]) {
    let filter = connect[start].enumerated().filter{$0.element && $0.offset != parent && $0.offset != stop}.map{$0.offset}
    count += filter.count
    filter.forEach {
        countConnectingWire(parent:start,start: $0, stop: stop, count: &count,connect: connect)
    }
}

 

4. ์ตœ์†Ÿ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

 

    return minCount

Source Code

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€