---
# System prepended metadata

title: 2359. Find Closest Node to Given Two Nodes
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}    
/* 設定連結 */
a,
.open-files-container li.selected a {
    color: #89FFF8;
    
}
a:hover,
.open-files-container li.selected a:hover {
    color: #89FFF890;
}
   
</style>

###### tags: `Leetcode`

# 2359. Find Closest Node to Given Two Nodes

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

## 題目
找到離兩個node最近的node。

定義：
設node1到x的距離為dist1，node2到x的距離為dist2
找到最小的max(dist1, dist2)的x
x即為答案
## 程式碼
```cpp=
class Solution {
public:
    int closestMeetingNode(vector<int>& edges, int node1, int node2) {
        const int n = edges.size();
        vector<int> dis1(n, -1), dis2(n, -1);
        //dis1紀錄node1能走到的點的距離，無法走到為-1
        //dis2紀錄node2能走到的點的距離，無法走到為-1
        int cur1 = node1, cur2 = node2, times = 0;
        //走訪node1能走到的所有點
        while(cur1 != -1){//直到走到不能走(到-1)
            if(dis1[cur1] == -1)//不重複走
                dis1[cur1] = times++;
            else break;
            cur1 = edges[cur1];
        }
        times = 0;
        //走訪node2能走到的所有點
        while(cur2 != -1){
            if(dis2[cur2] == -1)
                dis2[cur2] = times++;
            else break;
            cur2 = edges[cur2];
        }
        int smallest = n, node = -1;
        for(int i = 0;i <n;i++){
            //如果這個點node1或node2走不到
            if(dis1[i] ==-1 ||dis2[i] == -1)
                continue;
            if(smallest > max(dis1[i] , dis2[i]) ){
                smallest = max(dis1[i] ,dis2[i]);
                node = i;
            }
        }
        return node;
    }
};
```
## Date 
### 2023/1/25