๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป iOSun
article thumbnail

 

๋ฌธ์ œ ํ’€์ด

DFS๋ฅผ ์ด์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค.

 

 

 1. ์ด์ค‘๋ฐฐ์—ด์— ์—ฐ๊ฒฐ์ ์„ ๋„ฃ๋Š”๋‹ค. (vertex๋Š” 1๋ถ€ํ„ฐ ์‹œ์ž‘์ด๊ธฐ ๋•Œ๋ฌธ์— 0์€ ๋น„์›Œ๋‘ ) ex) [[], [3], [3], [1,2,4]]

 

 2. wires๋ฅผ ํฌ๋ฌธ์„ ๋Œ๋ฆฌ๋ฉฐ ์—ฐ๊ฒฐ์ ์„ ์ œ๊ฑฐํ•ด๋ณธ๋‹ค.

 

 3. ํ•˜๋‚˜ ์ œ๊ฑฐํ•œ ์ƒํƒœ์—์„œ DFS๋ฅผ ๋Œ๋ ค๋ณธ๋‹ค.

    ์ด๋•Œ DFS๋Š” DFS(๊ทธ๋ž˜ํ”„, ํ˜„์žฌ์ •์ )์ด๊ณ  DFS๊ฐ€ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋๊นŒ์ง€ ๊ฐ”์„ ๋•Œ ๋ฐฉ๋ฌธํ•œ ์ •์  ๊ฐœ์ˆ˜ count๋ฅผ ๊ตฌํ•œ๋‹ค.

    (ํ•œ ์ชฝ์˜ depth๋งŒ ๊ตฌํ•ด๋„ ๋‹ค๋ฅธ ํ•œ์ชฝ์˜ ๊ฐœ์ˆ˜๋ฅผ ์•Œ ์ˆ˜ ์žˆ๊ธฐ๋•Œ๋ฌธ์— ๊ทธ๋ƒฅ 1๋ถ€ํ„ฐ ๋Œ๋ฆฌ๊ณ  ๋๊นŒ์ง€ ๊ฐ€๋ณธ๋‹ค.)

 

 4. wires ํ•˜๋‚˜ ์ œ๊ฑฐํ• ๋•Œ๋งˆ๋‹ค ์†ก์ „ํƒ‘์˜ ๊ฐœ์ˆ˜ ์ฐจ์ด๋ฅผ ๊ตฌํ•œ๋‹ค. (๋‹ค์Œ wires๋บ„๋•Œ visited, count ์ดˆ๊ธฐํ™”)

 

 

์ฝ”๋“œ

func solution(_ n:Int, _ wires:[[Int]]) -> Int {
    
    var answer = 100
    var networks: [[Int]] = Array(repeating: [], count: n+1)
    var visited = Array(repeating: false, count: n+1)
    var count = 1 // ๋ฐฉ๋ฌธํ•œ ์†ก์ „ํƒ‘์˜ ๊ฐœ์ˆ˜
    
    // DFS(๊ทธ๋ž˜ํ”„, ํ˜„์žฌ์†ก์ „ํƒ‘ ๋ฒ„ํ…์Šค)
    func DFS(graph: [[Int]], v: Int) {
        for i in 0..<graph[v].count {
            let vertex = graph[v][i]
            if !visited[vertex] {
                visited[vertex] = true
                count += 1
                DFS(graph: graph, v: graph[v][i])
            }
        }
    }
    
    // arr์— ์—ฐ๊ฒฐ์ ์„ ๋„ฃ๋Š”๋‹ค. (์ธ๋ฑ์Šค 0์€ ๋ฌด์‹œ)
    for i in 0..<wires.count {
        let a = wires[i][0], b = wires[i][1]
        networks[b].append(a)
        networks[a].append(b)
    }
    
    // ์—ฐ๊ฒฐ์„ ํ•˜๋‚˜์”ฉ ๋Š์–ด๋ณด๋ฉฐ DFS ๋Œ๋ฆฐ๋‹ค.
    for i in 0..<wires.count {
        // ์—ฐ๊ฒฐ์„ ์„ ์ง€์šด๋‹ค.
        var graph = networks
        let a = wires[i][0], b = wires[i][1]
        let index1 = graph[b].firstIndex(of: a)!
        graph[b].remove(at: index1)
        let index2 = graph[a].firstIndex(of: b)!
        graph[a].remove(at: index2)
        
        // DFS ๋Œ๋ฆฌ๊ธฐ ์ „์— ๋ฐฉ๋ฌธ์—ฌ๋ถ€, ๋ฐฉ๋ฌธํ•œ ์†ก์ „ํƒ‘๊ฐœ์ˆ˜ ์ดˆ๊ธฐํ™” (1์€ ๋ฐฉ๋ฌธํ–ˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ณ  ์‹œ์ž‘)
        visited = Array(repeating: false, count: n+1)
        visited[1] = true
        count = 1
        DFS(graph: graph, v: 1)
        
        
        // ๋‹ค๋ฅธ ํ•œ์ชฝ ์†ก์ „ํƒ‘ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•ด์„œ ์ฐจ๋ฅผ ๊ตฌํ•œ๋‹ค.
        let anotherTopCount = abs(n-count)
        answer = min(answer, abs(count-anotherTopCount))
    }
    
    return answer
}

 

ํ›„๊ธฐ

์ •๋ง ์˜ค๋žœ๋งŒ์— ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ฅผ ํ’€๊ณ  ์žˆ๋‹ค. ์‹ค๋ ฅ์ด ๋‹ค์‹œ ์ฒ˜์Œ์œผ๋กœ ๋Œ์•„์˜จ ๊ฒƒ ๊ฐ™๋‹ค..^^

๊ทธ๋ ‡๊ฒŒ ์–ด๋ ค์šด ๋ฌธ์ œ๋Š” ์•„๋‹Œ ๊ฒƒ ๊ฐ™์€๋ฐ 2์‹œ๊ฐ„๋™์•ˆ ํ‘ผ๋“ฏ..

profile

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป iOSun

@iosun

ํฌ์ŠคํŒ…์ด ์ข‹์•˜๋‹ค๋ฉด "์ข‹์•„์š”โค๏ธ" ๋˜๋Š” "๊ตฌ๋…๐Ÿ‘๐Ÿป" ํ•ด์ฃผ์„ธ์š”!

profile on loading

Loading...