Swift solution - DFS, BFS


  • 0
    class Solution {
        func killProcess_DFS(_ pid: [Int], _ ppid: [Int], _ kill: Int) -> [Int] {
            var killed = [Int]()
            let children = buildChildren(pid, ppid)
            
            killAll(kill, children, &killed)
            
            return killed
        }
        
        func killProcess_BFS(_ pid: [Int], _ ppid: [Int], _ kill: Int) -> [Int] {
            var killed = [Int]()
            let children = buildChildren(pid, ppid)
            var queue = [Int]()
            
            queue.append(kill)
            while !queue.isEmpty {
                let kill = queue.removeFirst()
                killed.append(kill)
                if let childrenPID = children[kill] {
                    for child in childrenPID {
                        queue.append(child)
                    }
                }
            }
            
            return killed
        }
        
        private func buildChildren(_ pid: [Int], _ ppid: [Int]) -> [Int: Set<Int>] {
            var children = [Int: Set<Int>]()
    
            for i in 0..<pid.count {
                if children[ppid[i]] == nil {
                    children[ppid[i]] = Set()
                }
                children[ppid[i]]!.insert(pid[i])
            }
            
            return children
        }
        
        private func killAll(_ kill: Int, _ children: [Int: Set<Int>], _ killed: inout [Int]) {
            killed.append(kill)
            
            if let childrenPID = children[kill] {
                for child in childrenPID {
                    killAll(child, children, &killed)
                }
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.