2022/12/24

LeetCode 1436. Destination City

問題:找路徑 解法:key value JavaScript
/**
 * @param {string[][]} paths
 * @return {string}
 */
var destCity = function (paths) {
    if (paths.length < 1 || paths > 200) {
        return;
    }
    let key = null;
    const map = new Map();
    paths.forEach(s => {
        if (s[0] == s[1]) {
            return;
        }
        if (key === null) {
            key = s[0];
        }
        map.set(s[0], s[1]);
    });

    while (map.has(key)) {
        key = map.get(key);
    }

    return key;
}