微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 JavaScript 中检查图形是否循环

如何解决如何在 JavaScript 中检查图形是否循环

我想检查一个图形在 JavaScript 中是否是循环的。我有两个数组,第一个数组中的每个项目都与第二个数组的(相同索引)项目有关系。

举个例子:first = [4,2,3,1] second = [2,1,4]

所以有 4=>2,2=>3,3=>1 和 1=4 之间的关系。当您查看图表时,您可以看到它是循环的。

enter image description here

我写了这段代码,但它返回 false 虽然它应该为以下输入返回 true

first = [2,4] second = [3,3]

我怎样才能做到这一点?我需要使用图算法吗?

function ifGraphCyclic(first,second) {
    let nodes = new Map();
    let unique = [];
    for (let i = 0; i < first.length; i++) {
        nodes.set(first[i],second[i]);
    }

    for (let value of nodes.values()) {
        unique.push(nodes.get(value));
    }

    if (first.length === new Set(unique).size) {
        return true;
    }

    return false;
}

console.log(ifGraphCyclic([4,1],[2,4])) // return true
console.log(ifGraphCyclic([2,4],[3,3])) // *return false but should return true*
console.log(ifGraphCyclic([1,4,5,6],6,3])) // return false
console.log(ifGraphCyclic([1,4])) // *return false but should return true*

解决方法

您可以使用数组收集对象中节点的所有关系,并检查是否可以看到节点。

function ifGraphCyclic(first,second) {
    const nodes = first.reduce((r,v,i) => ((r[v] = r[v] || []).push(second[i]),r),{});

    for (let n of first) {
        const queue = [[n,[]]];

        while (queue.length) {
            const [node,seen] = queue.shift();
            if (!(node in nodes)) continue;
            if (seen.includes(node)) {
                console.log(...seen,n);
                return true;
            }
            seen.push(node);
            queue.push(...nodes[node].map(a => [a,[...seen]]));
        }
    }

    return false;
}

console.log(ifGraphCyclic([4,2,3,1],[2,1,4])); // 4 2 3 1 4
console.log(ifGraphCyclic([2,4],[3,3])); // 2 3 1 2
console.log(ifGraphCyclic([3,4,[1,2])); // 3 1 2 4 3
console.log(ifGraphCyclic([3,5])); // 2 4 3 1 5
console.log(ifGraphCyclic([1,5,6],6,3]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

,

将这两个数组视为数字排列的另一个想法 1,..,n: (这意味着 f(first[i]) = second[i])

因此,在以下示例中:first = [3,1] second = [1,2] 我们有以下功能:

f(3)=1,f(4)=3,f(2)=4,f(1)=2

那么,如果一个循环对你来说是一个长度小于 n 的循环, 那么检查这一点的直接方法是:

(0) define a function F as above
(1) Initialize array of n numbers,named A
(2) for i in A: 
(2.1) count = 0,tmp = i
(2.2) while (count < n):
(2.2.1) tmp = F(tmp)
(2.2.2) if tmp == i: set A[i] to 1 (break..)
(3) if your arrays is only zeros,then there is no cycle of length under than n

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。