알고리즘/그외

Leetcode 2359. Find Closest Node to Given Two Nodes - kotlin

우리로 2023. 1. 25. 16:56

 

 

https://leetcode.com/problems/find-closest-node-to-given-two-nodes/

 

Find Closest Node to Given Two Nodes - LeetCode

Find Closest Node to Given Two Nodes - You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a dire

leetcode.com

 

class Solution {
    val visited = BooleanArray(100001){false}
    fun closestMeetingNode(edges: IntArray, node1: Int, node2: Int): Int {
        val d1 = IntArray(100001){-1}
        val d2 = IntArray(100001){-1}
        visited[node1] = true
        dfs(edges = edges, node = node1, acc = 0, storage = d1)
        visited[node1] = false
    
        visited[node2] = true
        dfs(edges = edges, node = node2, acc = 0, storage = d2)
        visited[node2] = false

        var smallest = Int.MAX_VALUE
        var ind = -1
        for (i in 0 until edges.size){
            if(d1[i] != -1 && d2[i] != -1 && smallest > Math.max(d1[i], d2[i])){
                smallest = Math.max(d1[i] ,d2[i])
                ind = i
            }   
        }
        return ind
        
    }

    fun dfs(edges: IntArray, node: Int, acc:Int, storage: IntArray) {
        if(storage[node] < acc) {
            storage[node] = acc 
            val next = edges[node]

            if(next != -1 && !visited[next]) {
                visited[next] = true
                dfs(edges = edges, node = next, acc = acc + 1, storage = storage)
                visited[next] = false
            }
        }
    }
}

this solution starts by initialzing `d1` and `d2` of size 100_001. These arrays will store the distances from the two given nodes to all other nodes which includes both in the graph.

 

the method performs dfs algorithm starting from `node1`, and for each visited node, it stores the distnace as acc to that node in `d1`. 'node2' and 'd2' is same with. 

 

After both dfs are completed, the method iterates through the `edges` array, and for each index i it checks if the distance of that node in both `d1` and `d2` is not -1. if is not -`, it cheks if the max of both distance is smaller than the previous smallest value. if it is it updates the smallest value and the index.

 

Finally, it returns the index of the node that has the smallest max distance from both `node1` and `node2`